Skip to content

How much memory the java objects consume?

March 16, 2011

Recently I read the article to determine the size of java objects and found some interesting facts on object creation in java.

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.

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: