Java array size

When calculating the memory size of an array of objects, the following code gives "24 bytes" , as expected, which, as far as I know, consists of:

4bytes(element pointer)+16bytes(object header)+4bytes(element space) = 24bytes

 // with JVM argument -XX:-UseTLAB public static void main(String[] args) { long size = memoryUsed(); Object[] o = new Object[]{1}; //Object[] o = new Object[]{1L}; size = memoryUsed() - size; System.out.printf("used %,d bytes%n", size); //Output: used 24 bytes } public static long memoryUsed() { return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } 

But when the element type changed to Long (1L), the result is confusing, in most cases it "used 9.264 bytes" , can anyone help me enlighten? What is the difference in memory allocation between these two types of elements?

 // with JVM argument -XX:-UseTLAB public static void main(String[] args) { long size = memoryUsed(); //Object[] o = new Object[]{1}; Object[] o = new Object[]{1L}; size = memoryUsed() - size; System.out.printf("used %,d bytes%n", size); //Output: used 9,264 bytes } 
+5
source share
1 answer

There is a better way to calculate the size of an object as a whole, since there is a specialized tool for it called JOL .

It is not entirely correct how you think about it. The total size of this object will be 40 bytes . Let's see where this space comes from:

 12 bytes headers (8 bytes + 4 bytes, since there are two headers) 

You thought it was 16 bytes (8 + 8), but there is a compressed oops option that is enabled by default. You can disable it via -XX:-UseCompressedOops , in which case the size of the headers will be 16 bytes .

 4 bytes size of the array (arrays have an int size that is stored in headers) 4 bytes is the reference size of the Integer (1) 4 bytes alignment (since objects are 8 bytes aligned - this is the trick behind CompressedOops btw) 

So far you have 24 bytes for the array.

Now you store an integer inside it, that is, an object, and thus:

 12 bytes headers 4 bytes for the actual int value inside Integer 

So the total size is 40 bytes .

0
source

Source: https://habr.com/ru/post/1273970/


All Articles