Scott Hanselman

StringBuilders vs. String Concatenation

November 08, 2003 Comment on this post [0] Posted in Programming
Sponsored By

Some folks have said (you've heard them in the halls), “Oh ya, you should NEVER use String Concatenation, dude, use StringBuilder...ALWAYS.  Totally.”

Rico weighs in on this, and he's right on (emphasis mine):

I tend to give advice like "Many users find Stringbuilders useful for their concatenation pattens, consider using them and measure to see if they help you".  Wussy but safe :)

Big string -> small appends
It's substantially likely that appends will fit in the slop and so they're fast, this is the best case (buffer size becomes double the string when it no longer fits so on average the slop is half the current string length) (if there are lots of small appends to a big string you win the most using stringbuilder)

Big string -> big appends
While the string is comparable in size (or smaller) to the appends stringbuilder won't save you much, if this continues to the point where the appends are small compared to the accumlated string you're in the good case

Small string -> big appends
bad case, string builder will just slow you down until enough slop has built up to hold those appends, you move to "big string big appends" as you append and finally to "big string small appends" if/when the buffer becomes collossal

Small string -> small appends
could be ok if you had a good idea how big your string was going to get and preallocated enough so that you have sufficient slop for the appends. You might be able to do better if you just concated all the small appends together in one operation.

It's very hard to say which is faster/smaller in general... it's all about the usage pattern. [Rico Mariani]

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.