This post originated from an RSS feed registered with Java Buzz
by Kevin Dangoor.
Original Post: Beware of Java string memory allocation
Feed Title: Blue Sky On Mars
Feed URL: http://www.blueskyonmars.com/feed/?cat=8%2C13%2C14
Feed Description: Kevin Dangoor's Weblog of Technology, Entertainment and Life - Java only feed. For all articles, check out http://www.blueskyonmars.com
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.