views:

3457

answers:

3

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.

+4  A: 

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

Konrad Rudolph
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
@Avi: “doesn’t” refers to “`String.Replace` *always* creates a new string”, notice the emphasis on “always”.
Konrad Rudolph
+12  A: 

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
+5  A: 

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

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

VonC
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