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.
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 .
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With