Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VBNET
Expertise: Intermediate
Jan 5, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Process string faster with the StringBuilder class

You can think of a StringBuilder object as a buffer that can contain a string with the ability to grow from zero characters to the buffer's current capacity. Until you exceed that capacity, the string is assembled in the buffer and no object is allocated or released. If the string becomes longer than the current capacity, the StringBuilder object transparently creates a larger buffer. The default buffer initially contains 16 characters, but you can assign a different capacity in the StringBuilder's constructor or by assigning a value to the Capacity property:

' Create a StringBuilder object with capacity of 1000 characters.
Dim sb As New System.Text.StringBuilder(1000)
You can process the string held in the StringBuilder object with several methods, most of which have same name as and work similarly to methods exposed by the String class-for example, the Insert, Remove, and Replace methods. The most common way to build a string inside a StringBuilder object is by means of its Append method, which takes an argument of any type and appends it to the current internal string:

' Create a comma-delimited list of the first 100 integers.
Dim n As Integer
For n = 1 To 100
    ' Note that two Append methods are faster than a single Append
    ' whose argument is the concatenation of N and ",".
' Insert a string at the beginning of the buffer.
sb.Insert(0, "List of numbers: ")
Console.WriteLine(sb)   ' => List of numbers: 1,2,3,4,5,6,...
Because a StringBuilder doesn't allocate memory (or does it only when the internal buffer isn't long enough for the string being assign), it is much faster. For example, the code above is 100-150 faster than a similar loop based on the standard String class.
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date