官术网_书友最值得收藏!

Arrays

Variables can be a primitive type according to their declaration, or they may hold a reference to an object. A special object type is an array. When a variable holds a reference to an array, then it can be indexed with the [ and ] characters, along with an integral value consisting of 0 or a positive value ranging to one less than the array's length, to access a certain element of the array. Multi-dimensional arrays are also supported by Java when an array has elements that are also arrays. Arrays are indexed from zero in Java. Under or over indexing is checked at runtime, and the result is an exception.

An exception is special condition that interrupts the normal execution flow and stops the execution of the code or jumps to the closest enclosing catch statement. We will discuss exceptions and how to handle them in the next chapter.

When a code has an array of a primitive type, the array contains many memory slots, each holding the value of the type. When the array has a reference type, in other words, when it is an array of objects, then the array elements are references to objects, each containing the type. In the case of int for example, each element of the array is 32-bit, which is 4 bytes. If the array is a type of Integer, then the elements are references to objects, pointers, so to say, which is usually 64-bit using 64-bit JVM and 32-bit on 32-bit JVM. In addition to that, there is an Integer object somewhere in memory that contains the 4-byte value and also an object header that may be as much as 24 bytes.

The actual size of the extra information needed to administer each object is not defined in the standard. It may be different on different implementations of the JVM. The actual coding, or even the optimization of the code in an environment, should not depend on the actual size. However, the developers should be aware that this overhead exists and is in the range of around 20 or so bytes for every object. Objects are expensive in terms of memory consumption.

Memory consumption is one issue, but there is something else. When the program works with a large amount of data and the work needs the consecutive elements of the array, then the CPU loads a chunk of memory into the processor cache. It means that the CPU can access elements of the array that are consecutively faster. If the array is of a primitive type, it is fast. If the array is of some class type, then the CPU has to access memory to get the actual value, which may be as much as 50 times slower.

主站蜘蛛池模板: 平陆县| 鸡东县| 新密市| 玛曲县| 恩平市| 吐鲁番市| 西林县| 小金县| 理塘县| 龙泉市| 彭水| 蒲江县| 秭归县| 任丘市| 惠水县| 怀宁县| 嘉荫县| 江北区| 龙井市| 漠河县| 库尔勒市| 台湾省| 谷城县| 湟中县| 荣成市| 呼图壁县| 抚顺市| 衡山县| 马公市| 阿勒泰市| 梅河口市| 龙南县| 墨竹工卡县| 疏附县| 浑源县| 星子县| 贺兰县| 海兴县| 屯门区| 邛崃市| 桐柏县|