09 November, 2014

How much memory is allocated to the String object in Java

Size in bytes
String() object
Object header 16
Hash field 4
Reference to char array 4
Char[] array
Object header 16
Array length 4
Array size N*2

String allocates in memory at least (24+20+N*2) bytes, where N - number of characters in the string. If N=10 then string size = 64 bytes.

One million of these strings = 64 000 000 bytes. But also we need array or collection to store these strings.
This requires additional memory.
ArrayList<String>(1 000 000) ~= 4 000 000 bytes (4 bytes per reference to string object).

So, total size will be 68 000 000 bytes.

Gist code: Output:
3,355,792 Initial
1,217,624 After GC
218,921,768 Created list of strings
76,489,936 After GC
68,000,000 Expected size in memory
But if you have many similar strings, then using of String.intern() greatly reduces amount of allocated memory. Output:
3,355,792 Initial
1,217,792 After GC
106,750,232 Created list of strings
13,127,480 After GC
68,000,000 Expected size in memory
10x less memory! 6.8 megabytes instead of 68

No comments: