Reputation: 1
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?
Upvotes: 0
Views: 2587
Reputation: 857
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.
Upvotes: 0
Reputation: 7639
I have seen two cases where StringBuilder's tend to use large amounts of memory:
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.
Upvotes: 2
Reputation: 4542
Because of the doubling reallocation 2K for 500 characters would also be right, but not more. Here is a similar question.
Upvotes: 0
Reputation: 26118
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.
Upvotes: 0
Reputation: 1500635
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.)
Upvotes: 14