Memory usage of StringBuilder and StringBuffer
by, 04-26-2012 at 06:39 PM (851 Views)
The implementation of these classes is essentially done in similar manner through the shared subclasses & usage of their memory is also same. Difference comes when the turn of those methods come that are present at StringBuffer get synchronized. Here they will be referred as the string buffers generically for sake of simplicity however; comment at the usage of memory will be applied to both classes.
Objectís overhead is required by the string buffer, space for sake of int field and also space for reference, to underlying char arrays. This results into 16 bytes and padding is not needed. Char array would be requiring 12 overhead bytes, and then 2 bytes are required per character capacity, which roundup to multiple of eight. Therefore when initializsation of buffer is done to sixteen then it would give 60 bytes, which are rounded as 64 bytes.
It is important to note that when we call append(), the capacity of a string buffer doubles until it can hold the next character to be added. Thus, creating a default string buffer and then adding 17 characters will leave it with a capacity of 16*2=32 characters, each character position needing two bytes. and its memory usage will be 16+12+(32*2)=92, rounded up to 96 bytes.