-2

Reviewed

  1. size-of-a-byte-in-memory-java
  2. byte-in-java-takes-4-bytes-by-default

I am still trying to figure out why long and double in Java consuming 12 bytes instead of 8 bytes in memory

Sure there is wrong assumptions somewhere; please guide me..

I have analyzed it using two ways,

  1. Java VisualVM enter image description here
  2. Java Instrumentation based memory-measurer

Following is my logic/assumption/source info,

  1. Define a single float or long property in a class and check its memory footprint
  2. Object will carry its own Meta Data worth 12 bytes = [CLASS INFO OF 4 BYTES] + [FLAGS INFO OF 4 BYTES] + [LOCK INFO OF 4 BYTES]
  3. Class size will be Total Memory - Meta Data
  4. Result received is 12 bytes => 24 bytes (Total Memory) - 12 bytes (Meta Data)
  5. JDK: 1.8.0_65; Java HotSpot(TM) 64-Bit Server VM
  6. OS: Windows 8.1
  7. Test program

[ANSWER] Difference of 4 bytes is owing to Padding Applied by JVM. Thanks Andy Turner...

Community
  • 1
  • 1
InBravo
  • 73
  • 2
  • 7
  • @AndyTurner but inside the `DoubleClass` and `LongClass` there are primitive `long` and `double` variables. – radoh Mar 17 '16 at 14:19
  • @radoh `DoubleClass` and `LongClass` has its own meta data worth 12 bytes + 8 byte primitive `long` or `double` + 4 byte padding => 24 bytes total. I was not able to know that from where 4 bytes were coming in picture. Memory padding was the correct answer by Andy .... :) – InBravo Mar 18 '16 at 02:45

2 Answers2

2

Quoting this answer:

In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes

The extra 4 bytes is padding to get to a multiple of 8.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

you can check the size of double:

double numDouble=2;
long size=(long)(numDouble*Double.SIZE) / Byte.SIZE;
System.out.println(size);

output: 16

Musaddique S
  • 1,539
  • 2
  • 15
  • 36