Title | Use the StringBuilder class to concatenate strings quickly in Visual Basic .NET |
Description | This example shows how to use the StringBuilder class to concatenate strings quickly in Visual Basic .NET. |
Keywords | strings, variables, StringBuilder, concatenate, catenate |
Categories | Strings |
|
|
The example Generate random strings in Visual Basic .NET uses code similar to the following to generate a random string of letters.
|
|
' Make a word.
Dim word As String = ""
For j As Integer = 1 To num_letters
' Pick a random number between 0 and 25
' to select a letter from the letters array.
Dim letter_num As Integer = rand.Next(0, _
letters.Length - 1)
' Append the letter.
word &= letters(letter_num)
Next j
|
|
It may look like this code creates a single string but actually as it builds its result it creates a whole bunch of strings. For reasons of its own, .NET strings are immutable. That means you can never modify a string. Your code may look like it modifies a string but internally .NET destroys the old string and creates a new one.
In this example if num_letters is 10, then this code actually creates 11 strings. It starts with an empty string and adds the 10 letters one at a time, creating a new string each time.
The .NET Framework is optimized to make creating and destroying lots of strings reasonably fast but it still takes more time than it would if strings were implemented as simple arrays of characters.
The StringBuilder class manages a buffer of characters without turning them into a string so it can perform operations such as appending text more quickly than .NET can create a new string.
The following code does the same thing as the previous version except it use a StringBuilder instead of using &= to concatenate letters to its strings.
|
|
' Make a word.
Dim string_builder As New StringBuilder()
For j As Integer = 1 To num_letters
' Pick a random number between 0 and 25
' to select a letter from the letters array.
Dim letter_num As Integer = rand.Next(0, letters.Length _
- 1)
' Append the letter.
string_builder.Append(letters(letter_num))
Next j
|
|
There is some overhead to creating a StringBuilder object so it's not always faster. The class is most useful when you need to perform a very large number of operations on strings.
Note that both the &= and StringBuilder methods are very fast. In the example shown in the picture, the "slow" &= method took around 3.5 seconds to generate 1 million strings while StringBuilder took around 1.9 seconds. That means using StringBuilder saved only about 1.6 microseconds per string.
The moral is that you should generally use whichever method you find least confusing unless you're performing a huge number of string operations. I find &= easier to read so I use it most of the time.
|
|
|
|