Friday April 29th

Thursday April 28th

Wednesday April 27th

StringBuilder is not always faster

Here is something you may not know about string concatenation: StringBuilder is not always faster.

6 comments

would be nice to include string.concat and to include stringbuilder when you initialize the capacity instead of letting it default to 16 (or whatever the default size is).

also remove the creation of the stringbuilder object from the loop because that is probably taking up the extra time, not the concat.

StringBuilder s = new StringBuilder();
for (int i = 0; i <= 1000000; i++)
{
s.Append(i.ToString());
s.Append(i.ToString());
s.Append(i.ToString());
s.Length = 0;//resets stringbuilder
}

string s;
for (int i = 0; i <= 1000000; i++)
{
s = i.ToString();
s = s + i.ToString();
s = s + i.ToString();
}

string s;
for (int i = 0; i <= 1000000; i++)
{
s = string.Concat(i.ToString(), i.ToString(), i.ToString());
}


jamesewelch:

Thanks for the tip about string.concat. I didn't know that string.Concat works differently than using the "+" operator (Concat allocates space for all the strings involved at once and avoids extra copying).

As for moving the creation of the StringBuilder object outside of the loop, that would invalidate the comparison. The purpose of the loop is to measure the entire StringBuilder "operation" multiple times to get a more accurate elapsed time.

Moving StringBuilder out is more practical though. So if you want to compare impractical solutions, leave it in the loop. To me, the comparison is invalid if its code I'd never write.

I guess I didn't do a good job explaining the loop the first time. I am really comparing the code inside the loop. The for loop is only there to multiply the operation being measured thousands of times so that the final measurement is more accurate. It's the same idea as taking multiple samples and averaging them. If I didn't have the loop, the elapsed time would have been too small to accurately measure. For my test, the "operation" being measured is the concatenation of three string values, including the creation of the StringBuilder object.

@jamesewelch:
string.Concat is not _better_ than “+”, it’s identical. If you write “string s= a + b + c;” the compiler will actually emit “string s= string.Concat(a,b,c);”. It has to be one statement though, which is one reason why the sample loop didn’t use it. Thus you may rewrite the last loop to:
for (int i = 0; i <= 1000000; i++)
{
string s = i.ToString() + i.ToString() + i.ToString();
}
and it will produce the exact same IL. Have a look at http://ajdotnet.wordpress.com/2007/05/20/about-the-virtue-of-not-improving-performance/ for details.

HIH,
AJ.NET

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network