This post originated from an RSS feed registered with .NET Buzz
by Scott Hanselman.
Original Post: StringBuilders vs. String Concatenation
Feed Title: Scott Hanselman's ComputerZen.com
Feed URL: http://radio-weblogs.com/0106747/rss.xml
Feed Description: Scott Hanselman's ComputerZen.com is a .NET/WebServices/XML Weblog. I offer details of obscurities (internals of ASP.NET, WebServices, XML, etc) and best practices from real world scenarios.
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]