Improve the performance of StringBuilder in C# by setting its capacity to an estimate of final string length

When using StringBuilder 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.

Performance 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

Leave a Reply

Your email address will not be published. Required fields are marked *