30

If you have to use String.Replace() to replace test 50 times, you essentially have to create a new string 50 times. Does StringBuilder.Replace() do this more efficiently? E.g., should I use a StringBuilder if I'm going to be replacing a lot of text, even while I won't be appending any data to it?

I'm using .NET, but I assume this would be the same as Java and possibly other languages.

hangy
  • 10,765
  • 6
  • 43
  • 63
Jim
  • 11,229
  • 20
  • 79
  • 114
  • 3
    StringBuilder.Replace should use less memory, but it will not be any more performant than string.Replace http://www.codeproject.com/KB/cs/StringBuilder_vs_String.aspx – Sonic Soul Apr 28 '11 at 18:43

3 Answers3

30

This is exactly the type of thing StringBuilder is for - repeated modification of the same text object - it's not just for repeated concatenation, though that appears to be what it's used for most commonly.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
9

It depends if the size of the replacement is larger than the string replaced.

The StringBuilder over allocates its buffer, whereas a string only ever holds how ever many characters are in it.

The StringBuilder.Capacity property is how many characters the buffer will hold, while StringBuilder.Length is how many characters are in use.

Normally you should set StringBuilder.Capacity to a value larger then the expected resultant string. Otherwise the StringBuilder will need to reallocate its buffer. When the StringBuilder reallocates its buffer, it doubles it in size, which means after a couple reallocates it is probably significantly larger then it needs to be, by default capacity starts at 16.

By setting the Capacity value when you start (in the constructor for example) you save the reallocations of the StringBuilder's buffer. You can use StringBuilder.MaxCapacity to limit to maximum capacity that a StringBuilder can be expanded to.

David Grant
  • 3,447
  • 4
  • 29
  • 33
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 1
    A string creates with a StringBuilder will often hold more than the number of "useful" characters too - because a StringBuilder actually just contains a string which it uses as its buffer. – Jon Skeet Nov 13 '08 at 19:01
6

Yes, it is. String.Replace always creates a new string – StringBuilder.Replace doesn't.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    This is not entirely true, look at the source code. StringBuilder.replace() is calling AbstractStringBuilder.replace() which is calling AbstractStringBuilder.expandCapacity() if needed. AbstractStringBuilder.expandCapacity() is calling Arrays.copyOf() which creates a new array of chars - and this is the same as creating a new String. – Avi Y Jan 19 '10 at 06:48
  • 5
    @Avi: “doesn’t” refers to “`String.Replace` *always* creates a new string”, notice the emphasis on “always”. – Konrad Rudolph Jan 19 '10 at 13:30