I've been inspecting objects and I noticed that the size of a java.lang.String is always 24 bytes, regardless of the text it contains.
For example:
String str1 = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest";
String str2 = "test";
When computing the Strings' sizes using this method:
String test = "hello";
for(int i=0; i<10000; i++){
test += test + i;
}
log.debug( Agent.inst.getObjectSize( test ) );
It tells me that both strings are 24 bytes.
I know that all objects store only the address of the value and that value is static, but I don't understand what I'm observing. What's going on?
The technique to measure object size you are using is just too crude: it gives you the size of only the
String
instance itself and not of all the other instances it refers to—the size of its entire object graph. Existing tools use the crude call you have used, combined with reflection to walk the rest of the object graph, calling the same method in each step.Specifically, the
String
stores character data in achar[]
, whose object size is the most relevant to the overall memory occupied by aString
, for any longer string.