I have an object in Java which contains a String. I am curious how the memory usage of a String works. I'm trying to optimize memory usage for my program and the application will have about 10000 such objects. For a String such as "Hello World" what would the memory usage be?
Java uses two bytes per character *, so you would need to multiply the number of characters by two to get a rough approximation. In addition to the storage of the "payload", you would need to account for the space allocated to the reference to your string, which usually equals to the size of a pointer on your target architecture, the space for the length of the string, which is an int
, and the space for the cached hash code, which is another int
.
Since, "Hello World"
is 11 characters long, I would estimate its size as 2*11+4+4+4=34 bytes on computers with 32-bit pointers, or 2*11+8+4+4=38 bytes on computers with 64-bit pointers.
Note: this estimate does not consider the effects of interning string constants. When a string is interned, all references to the interned string share the same payload, so the extra memory per additional instance of an interned string is the size of a reference (i.e. the pointer size on the target architecture).
-XX:+UseCompressedStrings
option is used, in which case the strings that do not need UTF-16 use UTF-8 encoding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With