Sunday, September 18, 2011

Concatenating Strings Efficiently


StringBuilders should be reserved when the number of concatenations is unknown or large. 
Strings are immutable (not allowed to be changed). 

Dim sampleString As String = "I think the vegetables are : " _
sampleString &= "Tasty"

In the above example, the compiler will create a new string, allocate memory, copy the data from the original string and then copying the new data at the end of the existing string.

For a large number of concatenations, this operation is inefficient.


The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A string concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data.


Dim sampleString As String = "I think the vegetables are : " _
& "Tasty"


The string class is preferable if a fixed number of string objects are concatenated. Individual concatenation operations might be optmized by the compiler into a single operation.

 

Public Function Reproduce(
ByVal source As String,
ByVal iterations As Integer) As String
      Dim sampleStringBuilder As New System.Text.StringBuilder()
        For index As Integer = 0 To iterations
            sampleStringBuilder.Append(source)
        Next
      Return sampleStringBuilder.ToString()
End Function


A StringBuilder implementation is preferred when a large or unknown number of strings needs to be concatenated.


Resources:

http://www.yoda.arachsys.com/csharp/stringbuilder.html

http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

No comments:

Post a Comment