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 IntegerFor n = 1 To 100    ' Note that two Append methods are faster than a single Append    ' whose argument is the concatenation of N and ",".    sb.Append(n)    sb.Append(",")Next' 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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS