What is the size of an object in java

As we all know, java uses the following data types

byte Occupy 8 bits in memory short Occupy 16 bits in memory int Occupy 32 bits in memory long Occupy 64 bits in memory 

If I create a class like

 class Demo{ byte b; int i; long l; } Demo obj = new Demo(); 

Now my question is: obj size is < or > or = size b+i+l , which is 104 bytes . Please give me an explanation for a reasonable reason.

Thanks,
Anil Kumar C

+4
source share
6 answers

The size of the memory in memory depends on the architecture, mainly on whether the virtual machine is 32 or 64-bit. The actual implementation of VM also matters.

For each object, you need space for the object header (usually 2 * 8 bytes on 64-bit virtual machines), its fields (additional space for alignment depending on the implementation of the virtual machine). The final space is rounded to the nearest multiple word size.

+3
source

From http://www.javamex.com/tutorials/memory/object_memory_usage.shtml

  • The bare object takes up 8 bytes;
  • an instance of a class with one Boolean field takes 16 bytes: 8 bytes of the header, 1 byte for Boolean and 7 bytes of "padding", so that the size is a multiple of up to 8;
  • an instance with eight Boolean fields will also occupy 16 bytes: 8 for the header, 8 for Boolean; since this is already a few of 8, a gasket is not required;
  • an object with two long fields, three int fields and a boolean value:
    • 8 bytes for the header;
    • 16 bytes for two lengths (8 each);
    • 12 bytes for 3 integers (4 pieces);
    • 1 byte for boolean;
    • 3 more bytes of padding to round the total number from 37 to 40, a multiple of 8.
+5
source

It’s hard to say that it will be the size of obj in memory, the font size indicator will help developers, but in reality it is slightly different in memory. I advise you to read this article , it is really interesting.

+2
source

First you confuse bits and bytes.

Secondly, he will also need a pointer to "vtable", where information about his class is stored. This will most likely be 4 bytes (32 bits) on 32-bit systems and 8 bytes on 64-bit systems.

Finally, note that due to memory fragmentation, the total memory of the program may be higher than the sum of all objects.

+1
source

An object header can accept 8 bytes in a 32-bit JVM and 12 bytes in a 32-bit JVM.

Each primitive takes a number of bits (without specifying a byte)

The distribution of objects is 8 bytes, so there should be up to 7 bytes at the end of the object. that is, the actual used space is rounded to the next multiple of 8.

 class Demo{ // 8 or 12 bytes byte b; // 1 byte int i; // 4 bytes long l; // 8 bytes } Demo obj = new Demo(); 

Thus, the size of an object can take 24 bytes on a 32-bit JVM and 32 bytes on a 64-bit JVM.

0
source

I think this answer will make you deeply understand the size of the object.

What determines the size of a Java object?

0
source

Source: https://habr.com/ru/post/1411944/


All Articles