StringBuilder
The StringBuilder
class
in VB.NET optimizes and improves common String
operations. Appending, replacing and inserting are faster.
With ToString
, we can convert our data back into a String
. This operation is optimized to avoid copies. With StringBuilder
we have many built-in optimizations.
Append
exampleWe see a program that declares a new StringBuilder
. Then it uses a simple For
-loop and appends integers and 1-character strings to it.
System.Text
" lets us reference StringBuilder
more directly in the program.Imports System.Text Module Module1 Sub Main() ' Create StringBuilder and append to it in a loop. Dim builder As New StringBuilder() For i As Integer = 0 To 2 builder.Append(i).Append(" ") Next Console.WriteLine(builder) End Sub End Module0 1 2
AppendFormat
Next we use AppendFormat
. This function receives a format string
, usually with substitutions such as {0}, and parameters to fill those substitutions.
AppendFormat
, often yields code that is easier to read and understand.Imports System.Text Module Module1 Sub Main() ' StringBuilder declaration. Dim builder As New StringBuilder Dim number As Integer = 1 builder.AppendFormat("R: {0} ({1}).", "ABC", number) ' Print the resulting string data. Console.WriteLine(builder) End Sub End ModuleR: ABC (1).
Replace
This example creates a StringBuilder
with the constructor. Then it calls Replace()
to replace one substring with another. Performance is good. No string
temporaries are created.
StringBuilder
has the word "the" in it. After the Replace
method is run, it instead has the word "my."Replace()
returns a reference to the StringBuilder
. We can ignore this return value, or call another method on it.Imports System.Text Module Module1 Sub Main() Dim builder As New StringBuilder("Initialize the StringBuilder.") builder.Replace("the", "my") Console.WriteLine(builder.ToString) End Sub End ModuleInitialize my StringBuilder.
Replace
, all instancesThe Replace()
Function does not just replace the first instance of a string
it finds. It changes all of them, no matter how many there are.
Imports System.Text Module Module1 Sub Main() Dim builder As New StringBuilder("I see a cat, and the cat sees me.") ' Replace all instances of substring. builder.Replace("cat", "dog") Console.WriteLine("RESULT: {0}", builder) End Sub End ModuleRESULT: I see a dog, and the dog sees me.
For
-eachHere we use StringBuilder
in a For-Each
loop. Whenever we see Strings being appended in a loop, consider StringBuilder
. It can improve runtime performance.
String
array is declared. It contains 3 strings. A new StringBuilder
is instantiated with a certain value.For-Each
loop, the Dim
String
is assigned to each String
in the String
array.StringBuilder
has each string
(and a newline) appended to it. After the loop, the results are printed to the Console
.Imports System.Text Module Module1 Sub Main() ' String array for use in loop. Dim items As String() = New String() {"Indus", "Danube", "Nile"} ' Initialize new StringBuilder. Dim builder As StringBuilder = New StringBuilder("These rivers are cool:").AppendLine ' Loop over each item in Array. For Each item As String In items builder.Append(item).AppendLine() Next ' Write result. Console.WriteLine(builder.ToString) End Sub End ModuleThese rivers are cool: Indus Danube Nile
Insert
This modifies a StringBuilder
at the specified index. Here I specify the index 1, so the String
literal is inserted after the first character in the buffer.
Imports System.Text Module Module1 Sub Main() Dim builder As StringBuilder = New StringBuilder("A cat") Console.WriteLine(builder) ' Insert this string at index 1. builder.Insert(1, " fluffy") Console.WriteLine(builder) End Sub End ModuleA cat A fluffy cat
Remove
This erases characters from a StringBuilder
and collapse those following it. In this example, I remove four chars starting at index 1.
Imports System.Text Module Module1 Sub Main() Dim builder As StringBuilder = New StringBuilder("A big dog") Console.WriteLine(builder) ' Remove character starting at index 1. ' ... Remove 4 characters. builder.Remove(1, 4) Console.WriteLine(builder) End Sub End ModuleA big dog A dog
In appending, StringBuilder
is faster than String
. Consider this benchmark: we want to append 3-character string
(abc). We compare StringBuilder
and String
.
StringBuilder
to append a string
100 times.String
and its concatenation operator to append a string
100 times. This creates 100 strings.String
object results. Reducing allocations (with StringBuilder
) improves performance.Imports System.Text Module Module1 Sub Main() Dim m As Integer = 100000 ' Version 1: use StringBuilder. Dim s1 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Dim builder As StringBuilder = New StringBuilder For x As Integer = 0 To 99 builder.Append("abc") Next Next s1.Stop() ' Version 2: use String. Dim s2 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Dim str As String = "" For x As Integer = 0 To 99 str += "abc" Next Next s2.Stop() Dim u As Integer = 1000000 Console.WriteLine( s1.Elapsed.TotalMilliseconds.ToString("0.00 ms")) Console.WriteLine( s2.Elapsed.TotalMilliseconds.ToString("0.00 ms")) End Sub End Module 156.04 ms, StringBuilder Append 1020.00 ms, String concat
My research shows that appending two or three strings in a loop is faster than using StringBuilder
. But using StringBuilder
is faster for more than four iterations.
StringBuilder
in loops. It can avert a performance disaster in edge cases.HtmlTextWriter
HTML syntax uses lots of quotes and brackets. We can write HTML markup directly, without dealing with syntax: check out HtmlTextWriter
.
As developers, we will require StringBuilder
in many applications. It is an excellent performance optimization. Often, we use StringBuilder
in For-Each
loops.