When I am concatenating object values together to form a string in VB.NET, is there a difference in performance or a recommended best practice between using the &
concat or the +
concat with calls to .ToString()
on each object?
Example (which is faster or best practice):
Dim result1 As String = 10 & "em"
Dim result2 开发者_如何学编程As String = 10.ToString() + "em"
There is no performance difference. If you omit the .ToString()
call explicitly the compiler will essentially just fill that in for you. If you use Option Explicit you will be required to call the method or you'll get a compile error. I have heard good reasons for preferring both & and + semantically, so the choice there is really up to you.
I've never tried nor have I seen a performance test between the two and I doubt there's really a speed difference. I feel it's a better practice to use the 1st option because the .ToString() is inferred. Let the language hide that detail from you just as you would in a dynamic language.
Strings are immutable - meaning every time you manipulate a string, a new instance of a string object is created.
In these scenarios, to achieve better performance (and general best practice), use the StringBuilder
class of System.Text
.
In your example (im a C# coder, so apologize if my VB equivalent is incorrect)
Dim result As StringBuilder() = new StringBuilder()
result.Append("10")
result.Append("em")
Dim resultString As String = result.ToString()
Only when you invoke the .ToString()
method of the StringBuilder
object is an instance of the string created.
You should get used to using StringBuilder
as a best practice.
You can also use string.concat(str1, str2, str3, str4). This is an overloaded function and will take anywhere from 2-4 string arguments. With 3 or 4 strings to concat it is the fastest option as it is implemented to perform the concatenation in one operation which saves performance since strings are immutable.
Once you hit ~10+ strings you should use the stringbuilder class as suggested by RPM1984.
Otherwise, I suggest using '&' for string concatenations. It saves confusion as '+' can be easily confused for integer operations.
精彩评论