I have a for-loop with around 50k iterations. is it more efficient to do it like this:
Stringbuilder sb = new Stringbuilder();
for(int i = 0; i<50000; i++)
{
sb.Clear();
sb.Append("test") //Add everytime 9 different string even from parameters
string s = sb.ToString();
}
or it is more efficient to do it like this:
for(int i = 0; i<50000; i++)
{
Stringbuilder sb = new Stringbuilder();
sb.Append("..."); //the same like above
string s = sb.ToString();
}
So my question is: Is it faster to reinitialize the Stringbuilder in every loop or is it a better way to use the Stringbuilder.Clear()
function?
Or is it in my case of 9 different values in the string even better to concenate the strings?
Best Regards!
The first approach should be more performant, since it does (at least) 2x less
allocations. One string
instance will be allocated per iteration in any case, but there is no need to instantiate a new StringBuilder
each time.
In practice, the second approach will have even more allocations per iteration, unless you specify the initial capacity manually (and specify a large enough capacity). Otherwise the StringBuilder
might have to allocate several additional chunks (doubling its capacity each time).
Since calling StringBuilder.Clear()
simply resets the current length, chunks that are already allocated are not trimmed/collected by Clear()
, so the next iteration will already have the buffer prepared, and "probably" of the right size.