Search code examples
javakotlinmemory-managementreferenceheap-memory

Size of a Kotlin class that contains custom objects as it's data members


I understand that in Kotlin(or Java) an object is a referenced type. i.e.

private var Object1: Obj1? = Obj1()

Here var Object1 is a reference(8 bytes) to the instance of class Obj1(on Heap).

Thus, If I have a class such as:

class SampleClass {

private var IntVal: Int = 0
private var FloatVal: Float = 0F
private var Object1: Obj1? = Obj1 ()
private var Object2: Obj2? = Obj2 ()
}

Where Obj1 & Obj2 are custom classes:

class Obj1 {

private var IntVal1: Int = 0
private var IntVal2: Int = 0
private var IntVal3: Int = 0
}

class Obj2 {

private var FloatVal1: Float = 0F
private var FloatVal2: Float = 0F
private var FloatVal3: Float = 0F
}

Can I say that the size of the object of the SampleClass will be equal to Size of IntVal (Int: 4bytes) + size of FloatVal (float: 4bytes) + size of two object reference i.e. 8*2: 16bytes.

Thus, no matter what the size of class obj1 & obj2 is, the size of SampleClass will always be fixed (32bytes) as it holds the reference of the obj1 & obj2 objects and not the actual objects themselves.

Let me know if my understanding is correct or not.


Solution

  • It's true that an instance of SampleClass will only hold references to the objects, not the objects themselces. Those are independent from that instance. That said, the properties Object1 and Object2 are populated with new objects whenever a new instance of SampleClass is created. The total consumed memory therefore always includes the additional space needed for one Obj1 and one Obj2 instance.

    When you set Object1 and Object2 to null after a SampleClass instance was created you'll only remove the reference. The objects still exist in memory and take up memory. That's where the garbage collector comes into play: It observes al objects and count how many references exist for each. If the last reference to an object was removed it will delete the object from memory. That all happens automatically in the background, there is nothing for you to do for this to work. It will be undetermined, however, when exactly this happens. That's up to the internals of the garbage collector.

    Objects are therefore independent from each other and each object has its own size. They may be created together, but each object has its own lifecycle that is determined by how often it is referenced and will be cleaned up accordingly, also independent of other objects (unless they hold a reference, of course).

    How much memory an object actually consumes is hard to predict. It will at least be the sum of its references and the primitives it (and all its parents) contains, but there will be some additional overhead that is used by the JVM to manage the objects. That is not easily to be determined, though.