tutorials icon indicating copy to clipboard operation
tutorials copied to clipboard

Wrong object size on JVM Oracle build 1.8.0_192-b12

Open archenroot opened this issue 7 years ago • 7 comments

The size of String is still 24 bytes only no matter what I store :-)))

I just did dummy test and create string:

String string = "United Arabian Emirates fsdfasdfasdfadsfklasdk;lfjk;asdlkfj;asdlfjkasd;lfajkjsdl;kfjasd fjaksdf ;lasdkjf ;adldksjfasdf United Arabian Emirates asd;fk;ajsddfklja;slkfkjasd;fl adskjf;ladsk;jfalsdjfa;sd fjdUnited Arabian Emirates United Arabian Emirates";
printObjectSize(string);

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

That is not size of my object :-)

archenroot avatar Jan 04 '19 14:01 archenroot

Can you tell me what article and/or module you are referring to?

eric-martin avatar Jan 05 '19 02:01 eric-martin

@eric-martin - sure

https://www.baeldung.com/java-size-of-object

Code: https://github.com/eugenp/tutorials/tree/master/core-java/src/main/java/com/baeldung/objectsize

archenroot avatar Jan 05 '19 05:01 archenroot

I used finally:

 <!-- https://mvnrepository.com/artifact/org.spire-math/clouseau -->
        <dependency>
            <groupId>org.spire-math</groupId>
            <artifactId>clouseau_2.12</artifactId>
            <version>0.2.2</version>
        </dependency>

from https://github.com/non/clouseau which implemets in Scala and it works.

archenroot avatar Jan 05 '19 05:01 archenroot

Just a sample from docs

sizeOf(x) is defined as:

the sum of sizeOf(_) for all non-static members of x.
staticSizeOf(x) is defined as:

the sum of fullSizeOf(_) for all static members of x.
fullSizeOf(x) is defined as:

the sum of fullSizeOf(_) for all non-static members of x
added to the sum of fullSizeOf(_) for all static members of x.

Inspired by: https://github.com/non/clouseau

When I test approach of Clouseau quickly I get accurate results:

System.out.println(Calculate.sizeOf(string));
System.out.println(Calculate.staticSizeOf(string));
System.out.println(Calculate.fullSizeOf(string));

Outputs:

544
48
592

archenroot avatar Jan 05 '19 10:01 archenroot

Thanks @archenroot - We are investigating

eric-martin avatar Jan 06 '19 16:01 eric-martin

@eric-martin - I just provided more details from my case....

archenroot avatar Jan 06 '19 16:01 archenroot

Hey @archenroot. It's not an error, it's how Java initializes memory in JVM. Here is one answer from the StackOverflow:

Size of an empty string is:

32 bit HotSpot (16 bytes for String) 64 bit HotSpot (32 bytes for String) 64 bit HotSpot with compressed references (24 bytes for String) So the 24 bytes is the most common overhead.

It's not an error :)

maibin avatar Jan 07 '19 23:01 maibin