Java – does the order in the declaration of multidimensional arrays affect the memory used?
How many bytes do you want to allocate for a and B?
import android.graphics.Bitmap; Bitmap[][][] a = new Bitmap[1000][2][2]; Bitmap[][][] b = new Bitmap[2][2][1000];
Note that I'm just asking for pure array memory, no internal objects
Why do I ask because I'm writing an Android game To me, order is not important, but if there are differences, it would be good to save some
Solution
Yes, it makes a difference
In Java, 2D array is an array of 1D array. In addition to the space required to save the element itself, the array (such as all objects) has a title
So consider int [10] [2] versus int [2] [10], and assume a 32-bit JVM
>Int [2] [10] consists of a 2-element array and 2 10 elements There are 3 array objects and 22 elements. > Int [10] [2] consists of a set of 10 elements, and 10 arrays are 2 elements There are 11 array objects and 30 elements in total
If we assume that the title size is 3 32-bit words (a typical 32-bit JVM) and the reference is 1 32-bit words, then
>Int [2] [10] takes 3 * 3 22 * 1 = 31 words = 124 bytes > int [10] [2] takes 11 * 3 30 * 1 = 63 words = 252 bytes
Using the same logic, you can estimate the size of a larger number of arrays
But obviously, if the maximum size is the rightmost, less space is used
I use int arrays for math, but on 32 - bit machines, ints and references occupy the same number of bytes On 64 - bit machines, the reference can be the same as int or long, depending on the JVM options The title size may also be different Not quite sure... Potential platform dependencies
I didn't consider the space needed to keep the bitmap object itself, but the organization of the array is the same