Thursday, June 24, 2010

StringBuilder memory allocation

Today I was trying to understand a heap dump for a String that, when saved to a file, had 3 Mb in size. However, its retained dump was over 9 Mb! First, this String was a ThreadLocal variable - a library that we use to marshal this String into XML uses ThreadLocal (a good post on StringBuilders and ThreadLocal here).

A colleague tried to understand why it was 9Mb and found out a couple of things that we were not considering:
  • UTF16: each character consumes 2 bytes in a String to be represented. So, our 3Mb file would consume a minimum of 6Mb of memory space
  • StringBuilder allocation: whenever StringBuilder needs to expand its capacity, it doubles the current allocated memory. So, if we had 4.5Mb and needed one byte more, it would allocate an internal buffer of 9Mb. In our case, it was clear that 3 out of 9Mb had never been used for anything
Post a Comment