sizeof java object

前端 未结 6 1969
一生所求
一生所求 2020-11-30 13:25

How can we find out the size of a java object??

Example:

class Person{
    String name;  
    int age;  

    public Person(String n, int a){  
          


        
6条回答
  •  感动是毒
    2020-11-30 13:39

    Java has no built in sizeof operator.

    You could try and use a serialization method, by serializing an object to memory and getting the size of that data, but that wouldn't necessarily be the size you want.

    You could also have a method called sizeOf(), like this:

    // returns the size of this object in bytes
    int sizeOf()
    {
         int size = 0;
         size += name.Length * 2; // each character in name is 2 bytes, no?
         size += 4; // for n, which is 32 bits = 4 bytes
    }
    

    Note that this implementation doesn't include the metadata inside name, only the number of bytes necessary to make the char[] for it.

提交回复
热议问题