Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 334
Jim Avatar asked Nov 13 '08 18:11

Jim


People also ask

Is StringBuilder more efficient than string?

So from this benchmark test we can see that StringBuilder is the fastest in string manipulation. Next is StringBuffer , which is between two and three times slower than StringBuilder .

Is StringBuilder faster than string C?

StringBuilder has overhead, so string is faster for limited concatenations. If you are going to append or modify thousands of times (usually not the case) then StringBuilder is faster in those scenarios.

What is the best reason for using string builder instead of string?

This is because String is immutable - it cannot change its internal state. On the other hand StringBuilder is mutable. When you call append(..) it alters the internal char array, rather than creating a new string object.

Should I use StringBuilder or string?

If you are using two or three string concatenations, use a string. StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together. In short, use StringBuilder only for a large number of concatenations.


2 Answers

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.

like image 67
Michael Burr Avatar answered Sep 25 '22 10:09

Michael Burr


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.

like image 26
VonC Avatar answered Sep 24 '22 10:09

VonC