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? Eg, 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.
这正是StringBuilder所用的类型 - 对同一文本对象的重复修改 - 不仅仅是重复连接,尽管这似乎是最常用的。
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.
Yes, it is. String.Replace
always creates a new string – StringBuilder.Replace
doesn't.