Where are strings more useful than a StringBuilder?
Lot of questions has been already asked about the differences between string and string builder and most of the people suggest that string builder is faster than string. I am curious to know if string builder is too good so why string is there? Moreover, can some body give me an example where string will be more usefull than string builder?
It's not a case of which is more useful...
A String
is a String
- one or more characters next to eachother. If you want to change a string in someway, it will simply create more strings because they are immutable .
A StringBuilder
is a class which creates strings. It provides a means of constructing them without creating lots of reduntant strings in memory. The end result will always be a String
.
Don't do this
string s = "my string";
s += " is now a little longer";
or
s = s + " is now longer again";
That would create 5 strings in memory (in reality, see below).
Do this:
StringBuilder sb = new StringBuilder();
sb.Append("my string");
sb.Append(" is now a little longer");
sb.Append(" is now longer again");
string s = sb.ToString();
That would create 1 string in memory (again, see below).
You can do this:
string s = "It is now " + DateTime.Now + ".";
This only creates 1 string in memory.
As a side-note, creating a StringBuilder
does take a certain amount of memory anyway. As a rough rule of thumb:
StringBuilder
if you're concatenating strings in a loop. StringBuilder
if you're concatenating a string more than 4 times. StringBuilder is, as its name suggested, is used to build strings, whereas strings are immutable character-values. Use strings when you want to pass around character data, use StringBuilder when you want to manipulate character data.
StringBuilder is a better option when constructing and modifying strings through heavy looping or iterations.
Simple string operations such as a few concatenations or simply storing a string value suits a standard string object far better.
Similar question? String vs. StringBuilder
链接地址: http://www.djcxy.com/p/39798.html上一篇: 在绳索数据结构上拆分操作