Search This Blog

Sunday, June 28, 2009

C# String and StringBuilder

Which to choose?
Use string to represent basic data, such as header or title, string is excellent. For characters used in text processing, use StringBuilder.

C# string is immutable, so
string s = "my string";
s = "new string";
"my string" will be garbage collected.

If this happens frequently, such as string concatenation s3 = s1+s2 in a loop, use StringBuilder. It pre-allocated enough space at first.
StringBuilder s = new StringBuilder("more string here", 256);
s.Append("more here..");
s.AppendLine("more more...");

No comments: