YES, IT DOES! LET`S PUT IT TO TEST.
Since .NET compiles all managed languages (VB, C#, C++) to IL (Intermediate Language) instructions and String
type is part of CLS (Common Language Specification) all .NET Framework versions: 2.0, 3.0, 3.5, 4.0 optimizes String
literals concatenation as a part of compilation process.
For instance VB.NET code below:
Dim s As String = "A" & "B" & "C"
produces the following IL instruction:
L_0008: ldstr "ABC"
This clearly proves that compiler is optimizing String
literal concatenation (tested in: ildasm.exe)
However if the code obove is written in separate statements:
Dim s As String = "A"
s &= "B"
s &= "C"
no optimization is done and String
concatenation is executed at run-time (performance overhead). Same applies for a single line statements with data resolved at run-time (variables, properties, methods).
Use underscore _ to connect above statements into a single statement to enforce optimization:
Dim s As String = "A" _
& "B" _
& "C" _
and in case you need new lines between tokens use vbCrLf
(compile-time) constant to ensure optimization because using Environment.NewLine
(run-time) property provides no optimization.
Hope this helps you to get edge on performance!