Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does VB.NET optimize the concatenation of string literals?

Similar to this question, but for VB.NET since I learned this is a language thing.

For instance, would the compiler know to translate

Dim s As String = "test " + "this " + "function"

to

Dim s As String = "test this function"

and thus avoid the performance hit with the string concatenation?

like image 681
Larsenal Avatar asked Nov 14 '08 15:11

Larsenal


People also ask

Is string concatenation slow?

Each time strcat calls, the loop will run from start to finish; the longer the string, the longer the loop runs. Until the string is extensive, the string addition takes place very heavy and slow.

What is string concatenation in Visual basic?

Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows.

Which is faster string concatenation or the StringBuilder class?

Note that regular string concatenations are faster than using the StringBuilder but only when you're using a few of them at a time. If you are using two or three string concatenations, use a string.

How do you concatenate two strings in Visual basic?

String OperatorThe "&" operator joins two strings together. Example: Dim String1 As String = "123" Dim String2 As String = "456" Dim String3 As String String3 = String1 & String2 ' Results in "123456". The "+" operator may be used in place of "&".


1 Answers

Yes. It Does. I only tested VS 2008 but I strongly suspect previous versions did as well.

VB.NET

Public Class Class1


    Dim s As String = "test " + "this " + "function"

    Public Function test() As String
        Return s
    End Function

End Class

I.L. - Notice the string "test this function"

{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: call instance void [mscorlib]System.Object::.ctor()
    L_0006: nop 
    L_0007: ldarg.0 
    L_0008: ldstr "test this function"
    L_000d: stfld string ClassLibrary1.Class1::s
    L_0012: nop 
    L_0013: ret 
}
like image 145
Jason Hernandez Avatar answered Oct 13 '22 00:10

Jason Hernandez