Steps in the memory allocation process for Java objects

后端 未结 3 590
感动是毒
感动是毒 2020-12-01 21:10

What happens in the memory when a class instantiates the following object?

public class SomeObject{

    private String strSomeProperty;

          


        
3条回答
  •  庸人自扰
    2020-12-01 21:52

    Determining Memory Usage in Java by Dr. Heinz M. Kabutz gives a precise answer, plus a program to calculate the memory usage. The relevant part:

    1. The class takes up at least 8 bytes. So, if you say new Object(); you will allocate 8 bytes on the heap.
    2. Each data member takes up 4 bytes, except for long and double which take up 8 bytes. Even if the data member is a byte, it will still take up 4 bytes! In addition, the amount of memory used is increased in 8 byte blocks. So, if you have a class that contains one byte it will take up 8 bytes for the class and 8 bytes for the data, totalling 16 bytes (groan!).
    3. Arrays are a bit more clever. Primitives get packed in arrays, so if you have an array of bytes they will each take up one byte (wow!). The memory usage of course still goes up in 8 byte blocks.

    As people have pointed out in the comments, Strings are a special case, because they can be interned. You can reason about the space they take up in the same way, but keep in mind that what looks like multiple copies of the same String may actually point to the same reference.

提交回复
热议问题