0

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?

3

1 Answer 1

1

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 a char[], whose object size is the most relevant to the overall memory occupied by a String, for any longer string.

Sign up to request clarification or add additional context in comments.

3 Comments

what are the tools you say?
Thanks I will try this tool, if i have 2 object that link to same object (String for example) the Heap-space of VM have only 1 object and 2 references right?
Yes, that would be it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.