James Raitsev
James Raitsev

Reputation: 96381

Calculating object's memory footprint, clarification needed

When running

java -javaagent:ObjectSizeFetcherAgent.jar PersistentTime

I get

24

when ObjectSizeFetcherAgent does this

public class ObjectSizeFetcher {
    private static Instrumentation  instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

and when PersistentTime looks as follows

public class PersistentTime {

    List<String>    list    = new ArrayList<String>();

    public static void main(String[] args) {

        PersistentTime p = new PersistentTime();

        p.list.add("a");  // The number is the same with or without this
        p.list.add("b");  // The number is the same with or without this
        p.list.add("c");  // The number is the same with or without this

        System.out.println(ObjectSizeFetcher.getObjectSize(p));
    }
}

Why is adding elements to the list have no affect?

Upvotes: 1

Views: 364

Answers (2)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

Your PersistentTime object consists solely of one reference (to an array list).

24 bytes is typical for objects containing a single reference.

Note: referenced objects are not included in the computation. getObjectSize is not recursively collecting the combined object sizes. This is not generally possible: there could be infinite reference loops and such; I don't think there is a "deep size" computation easily available.

Upvotes: 1

johusman
johusman

Reputation: 3472

Because getObjectSize returns (an implementation-specific approximation of) the shallow size of the object. This means that it includes the size of the reference to the List, but not the space taken up by the list itself.

Upvotes: 2

Related Questions