StringBuilder
The StringBuilder class (System.Text namespace) represents a mutable (editable)
string. With a StringBuilder, you can Append, Insert, Remove, and Replace substrings
without replacing the whole StringBuilder.
StringBuilder’s constructor optionally accepts an initial string value, as well as a
starting size for its internal capacity (default is 16 characters). If you go above this,
StringBuilder automatically resizes its internal structures to accommodate (at a
slight performance cost) up to its maximum capacity (default is int.MaxValue).
A popular use of StringBuilder is to build up a long string by repeatedly calling
Append. This approach is much more efficient than repeatedly concatenating ordi-
nary string types:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 50; i++) sb.Append (i + ",");
To get the final result, call ToString():
Console.WriteLine (sb.ToString());
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,
In our example, the expression i + "," means that we’re still
repeatedly concatenating strings. However, this incurs only a
small performance cost in that the strings in question are small
and don’t grow with each loop iteration. For maximum per-
formance, however, we could change the loop body to this:
{ sb.Append (i.ToString()); sb.Append (","); }
AppendLine performs an Append that adds a new line sequence ("\r\n" in Windows).
AppendFormat accepts a composite format string, just like String.Format.
As well as the Insert, Remove, and Replace methods (Replace functions such as
string’s Replace), StringBuilder defines a Length property and a writable indexer for
getting/setting individual characters.
To clear the contents of a StringBuilder, either instantiate a new one or set its
Length to zero.
Setting a StringBuilder’s Length to zero doesn’t shrink its in-
ternal capacity. So, if the StringBuilder previously contained 1
million characters, it will continue to occupy around 2 MB of
memory after zeroing its Length. If you want to release the mem-
ory, you must create a new StringBuilder and allow the old one
to drop out of scope (and be garbage-collected).
No comments:
Post a Comment