3

I was just wondering that how much space will be reserved in the memory if i create a new object like"New Object()". As any object created on heap takes the space equals to the sum of size of its instance variables.

Java_Jack
  • 577
  • 1
  • 5
  • 8
  • possible duplicate of [What is the size of the object in java](http://stackoverflow.com/questions/10549381/what-is-the-size-of-the-object-in-java) – Andreas Fester May 17 '13 at 08:13
  • You can use [Java API](http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html) for this . – AllTooSir May 17 '13 at 08:13
  • Probably even more related: http://stackoverflow.com/questions/10386696/java-and-exact-reference-size-for-objects-array-and-primitive-types - the question is about references, but the answer also mentions object sizes – Andreas Fester May 17 '13 at 08:24

2 Answers2

15

As any object created on heap takes the space equals to the sum of size of its instance variables.

No, it takes more memory than that. There's additional memory required for a pointer to the type information, and for the monitor associated with the object (for synchronization purposes).

The exact size will vary by JVM (and particularly by processor architecture). It's also possible that for alignment purposes a JVM could implement a minimum size, but get a "first 4 bytes of fields free" policy. For example, suppose on a 64-bit JVM the type pointer took 8 bytes and the monitor information took 4 bytes, you might still want to allocate 16 bytes rather than 12 for alignment purposes - in which case an object with a single int field could take the same memory as a plain Object instance.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

The question will be a very broad one.

It depends on the class variable or you may call as states memory usage in java.

It also has some additional memory requirement for headers and referencing.

The heap memory used by a Java object includes

  • memory for primitive fields, according to their size (see below for Sizes of primitive types);

  • memory for reference fields (4 bytes each);

  • an object header, consisting of a few bytes of "housekeeping" information;

Objects in java also requires some "housekeeping" information, such as recording an object's class, ID and status flags such as whether the object is currently reachable, currently synchronization-locked etc.

Java object header size varies on 32 and 64 bit jvm.

Although these are the main memory consumers jvm also requires additional fields sometimes like for alignment of the code e.t.c.

Sizes of primitive types

boolean & byte -- 1

char & short -- 2

int & float -- 4

long & double -- 8

Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126