John,
Do not use + for string concatenation, use & for string concatenation.
As + is the addition operator while & is the string concatenation operator.
If you use ILDASM.EXE you will see that &= compiles to a call to
String.Concat.
So yes they result in the same IL code, and the speed would be the same.
I normally use the operator as it is a 'cleaner' syntax.
Just remember depending on what you are doing '&=' in a loop for example. It
will be faster to create a System.Text.Str ingBuilder object and call the
Append method.
For example (VS.NET 2003 syntax)
Dim startTime, endTime As DateTime
Dim time As TimeSpan
Dim s As String
startTime = DateTime.Now
For i As Integer = 0 to 10000
s &= "12345678901234 567890"
Next
endTime = DateTime.Now
time = endTime.Subtrac t(startTime)
Debug.WriteLine (time, "String")
startTime = DateTime.Now
Dim sb As New System.Text.Str ingBuilder
For i As Integer = 0 to 10000
sb.Append("1234 567890123456789 0")
Next
s = sb.ToString()
endTime = DateTime.Now
time = endTime.Subtrac t(startTime)
Debug.WriteLine (time, "String")
You will find the first loop takes significantly longer than the second
loop, especially as you increase the number of iterations. The reason for
this is that &= creates a new string for each iteration, while the
StringBuilder maintains a buffer internally that is larger than the
resultant string, this buffer is doubled each time the StringBuilder needs
more room. Resulting in better memory management.
Hope this helps
Jay
"John Ford" <zj**@C1h2e3z4F 5o6r7d8.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
For simple string concatenation, is there a difference between...
Dim s As String
s += "add this to string"
...and...
Dim s As String
s = String.Concat(s , "add this to string")
...and...
Dim s As String
s = s + "add this string"
Do they result in the same CLR code? If not, is one faster or
better in some way than the others?