Is StringBuilder.Replace() more efficient than String.Replace?

Jim picture Jim · Nov 13, 2008 · Viewed 13k times · Source

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.

Answer

Michael Burr picture Michael Burr · Nov 13, 2008

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.