Java and exact reference size for objects, array and primitive types

核能气质少年 提交于 2019-12-04 08:29:18

using a 64 bit JVM, pointer size should be 8 bytes,

Actually its usually 32-bit unless you have a maximum heap size of 32 GB or more heap. This is because Java uses references, not pointers (and each object is on an 8 byte, not 1 boundary)

The JVM can change the size of a reference depending on which JVM you use and what the maximum heap size is.

Object singletest = new Object(); will take 8 bytes to reference the Object plus the size of the Object

The object will use about 16 bytes of heap. It may or may not use 4 bytes of stack, but it could just use a register.

Object arraytest = new Object[10];

This will use about 16 bytes for the header, plus 10 times the reference sizes (about 56 bytes in total)

int singleint = new int; will take just 2 bytes, because int is a primitive type

int is always 32-bit bit, you can't create a newprimitive. As its notionally on the stack it might use 4-bytes of stack or it might only use a register.

int[] arrayint = new int[10]; will take 8 bytes to reference the position and 10*2 bytes for the elements

Again the object is likely to be the same size as the new Object[10] (56 bytes)

int[][] doublearray = new int[2][];
int[0][] = new int[5];
int[1][] = new int[10];

I wouldn't call it a doublearray as it could be confused with double[]

However the size is likkely to be about 16 + 2 * 4 for doublearray and 16 + 5*4 + 4 (for padding) and 16 + 10 * 4.

Memory allocated on the heap is aligned to an 8 byte boundary.

I call a new to instantiate, a pointer (or name it reference, because it's Java) of 8 bytes will be used plus 2+2bytes to store the integers into the class.

The reference is on the stack and usually this is not included.

The object has a header of about 16 bytes and the int values take up 2 * 4 bytes.

when I don't instantiate an object but I just declare it

Java doesn't let you declare Objects, only primitives and references.

what if I assign a null value?

That could change the value of the reference, but otherwise nothing happens.

if I declare an "int i" then I can immediately call i++ because no reference are used, just a portion of memory is setted on "0"

No heap will be used, possibly no stack will be used (possibly 4 bytes). Possible the JIT compiler will remove the code if it doesn't do anything.

maybe I'm not the only one interested

... but was not too afraid to ask. ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!