Search code examples
javaobjectsizeinstrumentation

Java Instrumentation finding object size


When calculating a Java object size

Class Test { 

   private String name = null;

   private List<String> myList = null;

}

Is it true the size of the Test class object will be different if i have one item in the list compared to thousand items in the list?


Solution

  • Well, that depends how you want to count it.

    The Test instance itself won't be bigger, it just has a reference to a List instance (or null, but that also takes up the same amount of space), and that List instance is its own object stored elsewhere on the heap (outside of your Test instance).

    The List instance will (depending on the implementation) also not vary in size, but it will in turn reference other objects (list entries, or arrays, or other things).

    In general, all class instances in Java take up a fixed memory allocation that is determined by the class and does not vary from instance to instance. The only thing that can have a "dynamic" size are arrays (but it's not all that dynamic, as it also is fixed on array creation time, so it can vary from instance to instance, but not over time for a given instance)

    If you want to calculate a "closure over the object graph" of all the memory needed for the Test object and all dependencies/contents (for example to estimate how much memory is needed to serialize it to a file), then yes, it would grow depending on how many objects are in the list.

    Also note that an ArrayList with ["foo", "foo"] might consume the same total amount of space as just ["foo", "foo", "foo"] (because the same single string instance is re-used three times, and the backing array has eight entries anyway). Or you might have multiple Test instances sharing the same List. So it's not that easy, and depends on how you want to count.