Search code examples
javainstrumentationobjectsize

Instrumenting java string object size gives incorrect result


I am using the java.lang.instrument.Instrumentation package to calculate the size of a java string. I follow the steps as listed here to create a java agent jar. Below is the application code that calls the java agent class

public static void main(String[] args) {
    String string = "A very long string which I have trimmed for this example";

    StringBuilder sb = new StringBuilder(string);
    for (int i=0; i<16000; i++) {
        sb.append(string);
    }

    printObjectSize(sb.toString());


}

private static long printObjectSize(Object object) {
    final long objectSize = ObjectSizeFetcher.getObjectSize(object);
    System.out.println("Object type: " + object.getClass() + ", size: " + objectSize + " bytes");
    return objectSize;
}

Here ObjectSizeFetcher is the class in the java agent that calls the instrumentation code internally. Irrespective of how big the string is, I always get the output as

Object type: class java.lang.String, size: 24 bytes

What could be going wrong?


Solution

  • A String object doesn't contain the String data but is a wrapper for a byte[] or char[] which contains the actual data.

    You need to extract the underlying array and get it's size as well.

    The String object should be about 24 bytes.