StringBuilder performance can be improved in C# by setting its capacity

When using StringBuilder in .NET most of times we likely just use the default constructor StringBuilder()… BUT if we have a rough estimate of how long our final string will be setting the capacity to this estimate can improve performance of StringBuilder dramatically.

StringBuilder performance in C# is improved when setting capacity because StringBuilder doesn’t have to resize the internal array which it stores the string in as many times as it would when using SB with the default constructor.

Below we can see in the 15 NumberOfRuns set that setting the capacity to 1000 performs betters than the default SB even though 1000 is a very high estimate (final sting length is actually 165). The further our estimate is away from the final string length the more memory is allocated… but this could be an acceptable trade-off in many app scenarios.

Set stringbuilder capacity

And note… it’s the same idea when we are using Lists in .NET too … we can set the capacity at creation time to improve speed.

One thought on “StringBuilder performance can be improved in C# by setting its capacity”

Leave a Reply

Your email address will not be published.