String concatenation is not efficient
in .NET because Strings are immutable. Changes made to a String
cause a new copy of the String to be created, resulting in
unnecessary overhead for each operation and extra garbage waiting to
be collected. This can result in very noticeable performance loss
especially when looping.
Make use of the StringBuilder class
when concatenating a String instead of adding to a String object.
There is some overhead when creating a StringBuilder, but this
overhead is offset after about five operations. Make a habit of using
the StringBuilder class when five or more operations are expected to
be done on the String.
Below is a short speed test to see how
dramatic of a difference there can be when looping.
Code-behind:
Dim
dateStart As
DateTime
Dim
dateEnd As
DateTime
Dim
timeDiff As
TimeSpan
'Run
for regular string concat-------------
Dim
strRegular As
String
= ""
dateStart
= Date.Now
For
i As
Integer
= 0 To
15000
strRegular = strRegular + i.ToString
Next
dateEnd
= Date.Now
timeDiff = dateEnd - dateStart
Me.LitSRegular.Text
= timeDiff.ToString
'------------------------------------------
'Run
for stringbuilder---------------------
Dim
strbTest As
New
StringBuilder()
dateStart
= Date.Now
For
i As
Integer
= 0 To
15000
strbTest.Append(i.ToString)
Next
dateEnd
= Date.Now
timeDiff = dateEnd - dateStart
Me.LitSBuilder.Text
= timeDiff.ToString
'------------------------------------------
Front-end:
Regular
string concatenation: <asp:Literal
ID="LitSRegular"
runat="server"></asp:Literal>
<br
/>
StringBuilder: <asp:Literal
ID="LitSBuilder"
runat="server"></asp:Literal>
Running the above code will provide
similar results to the following:
Regular string concatenation:
00:00:01.8281250
StringBuilder: 00:00:00.0156250