Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory usage of String in Java

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?

like image 606
RagHaven Avatar asked Nov 04 '13 20:11

RagHaven


1 Answers

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).


* Unless the -XX:+UseCompressedStrings option is used, in which case the strings that do not need UTF-16 use UTF-8 encoding.
like image 95
Sergey Kalinichenko Avatar answered Oct 27 '22 22:10

Sergey Kalinichenko