Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

java - Does order in a declaration of multidimensional array have an influence on used memory?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 bytes
  • int[10][2] takes 11*3 + 30*1 = 63 words = 252 bytes

Apply 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...