How many bytes will be allocated 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 only asking about the memory taken by pure arrays, no objects inside.
Why I'm asking? Because I'm writing an Android game. For me the order doesn't matter, but if there is a memory difference, it will be good to save some.
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order.
Row-major order and column-major order are methods for storing multidimensional arrays in linear storage such as random access memory.
Multidimensional Arrays in C / C++ Data in multidimensional arrays are stored in row-major order. The general form of declaring N-dimensional arrays is: data_type array_name[size1][size2]....[sizeN];
Yes it does make a difference.
In Java, a 2D array is an array of 1D arrays, and arrays (like all objects) have headers in addition to the space needed to hold the elements themselves.
So consider int[10][2]
versus int[2][10]
, and assume a 32 bit JVM.
int[2][10]
consists of one array of 2 elements, and 2 arrays of 10 elements. Total - 3 array objects + 22 elements.int[10][2]
consists of one array of 10 elements, and 10 arrays of 2 elements. Total - 11 array objects + 30 elements.If we assume that the header size is 3 32-bit words (typical for a 32bit JVM) and a reference is 1 32-bit word, then
int[2][10]
takes 3*3 + 22*1 = 31 words = 124 bytesint[10][2]
takes 11*3 + 30*1 = 63 words = 252 bytesApply the same logic and you can estimate the size of arrays with higher numbers of dimensions.
But it is clear that you use less space if the largest dimension is the right-most one.
I've done the math with int
arrays, but on a 32 bit machine an int
and a reference
occupy the same number of bytes. On a 64 bit machine, a reference can be the same size as an int
or a long
, depending on JVM options. The header sizes may also be different .... not exactly sure ... potentially platform dependent.
I've not accounted for the space required to hold the Bitmap
objects themselves, but it is the same however you organize the arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With