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

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.

主站蜘蛛池模板: 若羌县| 响水县| 新闻| 吴桥县| 常德市| 旬邑县| 辛集市| 鸡西市| 耒阳市| 鄯善县| 溧水县| 德钦县| 玉溪市| 玛纳斯县| 阜宁县| 苏州市| 汨罗市| 惠安县| 新昌县| 伊春市| 梁山县| 梁山县| 沧源| 盈江县| 靖西县| 醴陵市| 罗源县| 普洱| 濮阳市| 东台市| 施秉县| 大石桥市| 永康市| 呈贡县| 扬州市| 于田县| 襄樊市| 安泽县| 鄂州市| 吴旗县| 高淳县|