Thursday, December 8, 2011

How much memory the java objects consume?

For an empty class:

public class TestClass {

}

size of the TestClass Object is 2 * Reference = 2*4 = 8 bytes.

For a class with primitive – int:

public class TestClass {
int i=0;
}

size = 2 * reference + size of int = 2*4 + 4 = 12 = 16 bytes (word aligned)

For a class with primitive – long:
public class TestClass {
long i=0;
}

size = 2 * reference + size of long= 2*4 + 8 = 16 bytes.

similarly for float and double , the size is 16 bytes.

Taking the wrapper classes,

public class TestClass {
Integer i= new Integer(0);
}
size = 2 * reference for TestClass Object + 2*Reference for Integer
object + size of int

= 2*4 + 2*4 + 4 = 32 bytes (word aligned)

Similarly the sizes for the objects with the Long, Float and Double
fields are32 bytes.

Instead of using the 'new' key word for the Integer instantiation, if
we use Integer i=1; then the results are different.

public class TestClass {
Integer i=0;
}

size = 5152 bytes.

The reason being Integer i=0; is inferred as Integer i= Integer.value(0);

A cache is initialized with all the possible int values varying from
-128 to 127. The 'i' is initialized with the value zero from the
cache.

If you take the String instantiation,

public class TestClass {
String s=new String("i");
}

it consumes about 40 bytes of memory where as,

public class TestClass {
String s="i";
}

consumes about 16 bytes of memory. It took less bytes since "i" is
from the string pool.

No comments:

Post a Comment