0

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?

Menno
  • 1
  • 1

5 Answers5

14

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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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.

Philipp
  • 7,199
  • 1
  • 22
  • 16
0

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.

Tendayi Mawushe
  • 25,562
  • 6
  • 51
  • 57
0

Because of the doubling reallocation 2K for 500 characters would also be right, but not more. Here is a similar question.

Community
  • 1
  • 1
candiru
  • 4,424
  • 2
  • 22
  • 16
0

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.

Mike
  • 777
  • 3
  • 16
  • 41
  • Faster than what? Safer? Be aware that StringBuilder is _not_ thread safe, in contrast to StringBuffer. BTW this question is almost 8 years old... – Andy May 05 '17 at 17:56
  • Faster than StringBuffer.Anythng else you need to understand. – Mike May 05 '17 at 18:11