Beware of Java string memory allocation

Apr 27, 2005 19:57 · 134 words · 1 minute read

Charles Miller and other Atlassian folks were digging into a memory issue and found out that memory allocation and garbage collection for Strings and StringBuffers may not be what you’re expecting. The main thrust of it is that there are some optimizations to speed the common cases that can result in considerable memory waste if you’re not aware of the implementation. (For example, if you have a StringBuffer with a 32K capacity and do a toString on it, that new String will take up 32K of memory even if you only had 1 byte in the StringBuffer.)

To me, that actually sounds like a bug. It’s probably worth a couple microseconds (or less) to see if the data is significantly smaller than the allocated space and then do a copy if that’s the case.