I read somewhere that the Java StringBuilder uses around 1 mb for 500 characters. Is this true and if so, isn't that a bit extreme? Is the StringBuilder doing some incredible things with this amount of memory? What is the reason and does this mean I should not make too much use of this class?
-
3Where did you read this?McDowell– McDowell2009年11月10日 11:40:24 +00:00Commented Nov 10, 2009 at 11:40
-
Somewhere on the Internet, of course.Bart Kiers– Bart Kiers2009年11月10日 14:34:27 +00:00Commented Nov 10, 2009 at 14:34
5 Answers 5
No, that's complete rubbish - unless you create a StringBuilder with a mammoth capacity, of course.
Java in general uses 2 bytes per char. There's a little bit of overhead in String and StringBuilder for the length and the array itself, but not a lot.
Now 1K for 500 characters is about right... I suspect that was the cause of confusion. (Either you misheard, or the person talking to you was repeating something they'd misheard.)
Comments
I have seen two cases where StringBuilder's tend to use large amounts of memory:
- When the StringBuilder is created with an insane initial-capacity.
- StringBuilder's who were "cached" to "save" object-allocation time.
So in the second case a StringBuilder might consume 1Mb of memory if some code, which used the SB earlier, stored a very big string in it. That's because it will only grow but not shrink its internal char-array.
Both cases can (and should) easy be avoided.
Comments
This information is erroneous, do you remember what the source of this information was? If so you should correct it. Java normally uses 2 bytes per character.
Comments
Because of the doubling reallocation 2K for 500 characters would also be right, but not more. Here is a similar question.
Comments
I think StringBuilder is the best choice to use. It is faster and safer too. It depends on the scenario. If you have String literal that doesn't change frequently then I would say String is a better choice because it is immutable else StringBuilder is right there. Now for the space that you are talking about I haven't heard that any where.