Manipulate Strings Quickly with StringBuilder

Problem

You need to perform a repeated string manipulation, and you want to optimize performance.

Solution

Use the System.Text.StringBuilder class to perform your string operations, and convert the final result into a string by calling ToString.

Discussion

Ordinary .NET strings are immutable. Changing just a single character causes the whole string to be thrown away and a new string to be created.

The StringBuilder class represents a buffer of characters that can be directly modified. These direct modifications are faster than repeatedly generating a new String object. However, using the StringBuilder might introduce a small overhead because you need to copy the string into the StringBuilder before performing ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.