The World’s Leading Microsoft .NET Magazine
   
 
Jerry Dixon

String Concatenation, StringBuilder, and String.Format

posted Sunday, 8 January 2006

By now, most people should know that string concatenation in .NET is an expensive process.  It is SLOW.  There are reasons for this that make plenty of sense, but the end result is that you shouldn't concatenate lots of strings and expect your program to run quickly.  The most common way to avoid this performance hit is to use the StringBuilder class.  It is written specifically to avoid the speed penalties suffered by concatenation suffers.  But what about String.Format?  I recently decided to test the performance of all three of these method.  I was surprised by the results.

Here are my test methods:

Private Sub FormatTest()
    
Dim x As
String
    
Dim a As
String
    
Dim b As
String
    
Dim c As
String
    
Dim d As
String
    
Dim e As String

     For i As Integer = 1 To 100000
          a = i.ToString
          b = (i * 2).ToString
         
c = (i + 1).ToString
          d = (i - 1).ToString
          e = (i * 3).ToString

          x = String.Format("Result {0}, {1}, {2}, {3}, {4}", a, b, c, d, e)
     Next
End Sub

Private Sub ConcatTest()
    
Dim x As
String
    
Dim a As
String
    
Dim b As
String
    
Dim c As
String
    
Dim d As
String
    
Dim e As String

     For i As Integer = 1 To 100000
          a = i.ToString
          b = (i * 2).ToString
         
c = (i + 1).ToString
          d = (i - 1).ToString
         
e = (i * 3).ToString

          x = "Result " & a & ", " & b & ", " & c & ", " & d & ", " & e
     Next
End Sub

Private Sub StringBuilderTest()
    
Dim x As
StringBuilder
    
Dim a As
String
    
Dim b As
String
    
Dim c As
String
    
Dim d As
String
    
Dim e As String

     For i As Integer = 1 To 100000
          a = i.ToString
          b = (i * 2).ToString
          c = (i + 1).ToString
         
d = (i - 1).ToString
          e = (i * 3).ToString

          x = New StringBuilder
          x.Append(
"Result "
)
          x.Append(a)
          x.Append(
", "
)
          x.Append(b)
          x.Append(
", "
)
          x.Append(c)
          x.Append(
", "
)
          x.Append(d)
          x.Append(
", "
)
          x.Append(e)
    
Next
End Sub

 I ran each method five times and averaged the results.  Here they are:

MethodTicks
 String.Format 4,062,500 
 String Concatenation 2,781,250 
 StringBuilder 3,531,250 

StringBuilder wasn't the fastest, and String.Format lost big time.  I guess I'll start concatenating strings again.

links: digg this    del.icio.us    technorati