tags:

views:

141

answers:

3

If I have:

int c[] = new int[10];

and

int a[][] = new int[2][3];

and in generally

an n*m*..*j array

how can I calculate the real memory usage considering also the references variables?

+1  A: 

The int[] or int[][] is not a primitive data type. It is an Object in Java. And with an Object, the size cannot be calculated straight away.

Bragboy
where does `+sizeof(int)` come from?
Bakkal
A reference might not be 4 bytes depending on your platform.
Matti Virkkunen
@Matti: Agreed. The whole stuff is not correct. Let me edit it.
Bragboy
Writing the reference memory as `sizeof(int)` is misleading, even if on that particular platform it is 4 bytes.
Bakkal
I think if we keep on editing to make it *technically correct* we will settle with "there is no easy accurate way" :P
Bakkal
+5  A: 

If you want an accurate answer, you can't. At least not in any easy way. This thread explains more.

The trouble with Bragaadeesh's and Bakkal's answers are that they ignore overhead. Each array also stores things like the number of dimensions it has, how long it is and some stuff the garbage collector uses.

For a simple estimate, you should be fine by using the calculations from the other answers and adding 100-200 bytes.

Jørgen Fogh
This answer is correct. There's always overhead due to type/GC information and whatnot. Plus there's the fact that Java doesn't have a true multidimensional array, only jagged arrays, which end up generating quite a bit of that overhead.
Matti Virkkunen
how is represented in memory a multidimensional array?
xdevel2000
I deleted my answer since I know of no way to calculate the *exact* size inclusive of overhead.
Bakkal
@xdevel2000: Java does not have multidimensional arrays. Only arrays of arrays.
Matti Virkkunen
@Matti Virkkunen: True. The VM still keeps track of how many layers of arrays are nested, so you can't assign an array of chars to an array of arrays of chars.
Jørgen Fogh
+1  A: 

you'll probably get the best approximation from this: http://java.sun.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize(java.lang.Object)

This article, and this comprehensive one demonstrates/details this approach

Ryan Fernandes