String.Concat

  • Thread starter Thread starter John Ford
  • Start date Start date
J

John Ford

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?
 
John Ford said:
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?

Yes


s = s & ...
and
s &=
also

If not, is one faster or
better in some way than the others?

No
 
Hello,

John Ford said:
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?

Have a look at the code using ildasm.exe.

Notice that it's recommended to use the & operator to concatenate strings in
VB .NET.

HTH,
Herfried K. Wagner
 
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.StringBuilder 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 &= "12345678901234567890"
Next
endTime = DateTime.Now
time = endTime.Subtract(startTime)
Debug.WriteLine(time, "String")

startTime = DateTime.Now
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 to 10000
sb.Append("12345678901234567890")
Next
s = sb.ToString()
endTime = DateTime.Now
time = endTime.Subtract(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
 
Back
Top