How often have you been told to use StringBuilder to concatenate strings in .NET? My guess is often enough. Here is something you may not know about string concatenation: StringBuilder is not always faster. There are already many articles out there that explain the why’s, I am not going to do that here. But I do have some test data for you.
When concatenating three values or less, traditional concatenation is faster (by a very small margin)
This block of code took 1484 milliseconds to run on my PC:
for (int i = 0; i <= 1000000; i++){
// Concat strings 3 times using StringBuilder
StringBuilder s = new StringBuilder();
s.Append(i.ToString());
s.Append(i.ToString());
s.Append(i.ToString());
}
And this one, using traditional concatenation, took slightly less time (1344 milliseconds):
for (int i = 0; i <= 1000000; i++){
// Concat strings 3 times using traditional concatenation
string s = i.ToString();
s = s + i.ToString();
s = s + i.ToString();
}
The above data suggests that StringBuilder only starts to work faster once the number of concatenations exceed 3.
Building strings from literals
When building a large string from several string literals (such as building a SQL block, or a client side javascript block), use neither traditional concatenation nor StringBuilder. Instead, choose one of the methods below:
+ operator
// Build script blockstring
s = “<script>”
+ “function test() {”
+ ” alert(’this is a test’);”
+ ” return 0;”
+ “}”;
The compiler concatenates that at compile time. At run-time, that works as fast as a big string literal.
@ string literal
I sometimes use the @ string literal which allows for newlines (I find this syntax is harder to maintain, formatting-wise, than using the + operator):
string s = @”<script> function test() { alert(’this is a test’); return 0; }”;
Both methods above run about 40 times faster than using StringBuilder or traditional string concatenation.
Rules of Thumb
- When concatenating three dynamic string values or less, use traditional string concatenation.
- When concatenating more than three dynamic string values, use StringBuilder.
- When building a big string from several string literals, use either the @ string literal or the inline + operator.
Ref: http://www.chinhdo.com/chinh/blog/20070224/stringbuilder-is-not-always-faster/
Tags: stringbuilder