1

I am trying understand about the size that a Java object will be allocated with when created using a new operator.

Consider that i am creating a class

public class NewClass {

    NewClass() { }

}

when i create an instance of NewClass using NewClass nc = new NewClass();. what is the size of the NewClass that gets created in the heap?

~ Jegan

Robert Munteanu
  • 67,031
  • 36
  • 206
  • 278
Jegan Kunniya
  • 986
  • 3
  • 17
  • 27

2 Answers2

9

Profiling is the best way, but you can get a good estimate like so:

8 bytes per object (bare overhead), plus fields.

  • Primitive Fields: as listed in Java. Note: booleans need 1 full byte.
  • Object fields: 1 pointer (4 bytes on 32-bit VM, 8 on 64-bit), plus size of object itself (if not a reference to a preexisting object)
  • Arrays: 4 bytes + object/primitives for elements
  • Strings: far, far too much. IIRC, 24 bytes + 2 bytes/character. Might be more.

The final result is increased to the nearest multiple of 8 bytes.

See also my example here for how to calculate memory use on a more complex object. Note: these rules may vary with VMs, and may change as newer versions of the VM come out. My estimate only applies to the Sun JVM, although I suspect IBM's results will be similar.

Community
  • 1
  • 1
BobMcGee
  • 19,824
  • 10
  • 45
  • 57
  • Note that "size of object itself" may not be applicable if you're referencing objects that already exist. Same goes for the array elements. – Craig Walker Jan 14 '10 at 06:54
  • I thought that was assumed, but fair enough -- I added a couple qualifiers to make it clear under what conditions this estimate applies. – BobMcGee Jan 14 '10 at 13:40
  • I would have said the bare overhead is 16 bytes. (On 64-bit JVMs at least) – Peter Lawrey Jan 20 '10 at 18:07
  • @Peter: I think you're right (I read it was 2 machine words in one place), but can you cite a source to confirm that? – BobMcGee Jan 24 '10 at 23:33
  • Note for arrays of arrays you take the hit twice, e.g. double[3][2] is 64 bytes, whilst double[6] is only 52 bytes. Languages with multi-dimensional array support, e.g. C#, don't have this problem. – Sam Aug 24 '10 at 16:27
0

I think you need to use a profiler to measure this. You may use JProfiler or YourKit profilers for this.

Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138