AntiTcb
AntiTcb

Reputation: 649

Visual Basic Best Implementation of Creating an Array

So I fiddled (please don't shoot me) around with seeing what was the faster implementation for arrays after browsing through MSDN's docs.

https://msdn.microsoft.com/en-us/library/h63fsef3.aspx This states that:

Use the { } syntax when you declare and initialize arrays of basic data types. >For example, use the following syntax:

   Dim letters5() As String = {"a", "b", "c"}

Do not use the following syntax:

   Dim letters6(2) As String
   letters6(0) = "a"
   letters6(1) = "b"
   letters6(2) = "c"`

I understand that the article was written in the context of coding conventions, and not necessarily geared toward coding for speed/efficiency, but assuming I tested correctly in my dotnetfiddle, the latter syntax that Microsoft prompts you to not use is faster, correct?

https://dotnetfiddle.net/fqK5aQ

Upvotes: 1

Views: 104

Answers (1)

Mark
Mark

Reputation: 8160

Interesting. Looking at the generated IL in LINQPad (not sure how this compares to a normal compile - I assume it's the same, but could be wrong), the IL for the two ways to initialize the array is slightly different.

Dim letters5() As String = {"a", "b", "c"}
IL_0000:  ldc.i4.3    
IL_0001:  newarr      System.String
IL_0006:  stloc.1     // VB$LW$t_array$S0
IL_0007:  ldloc.1     // VB$LW$t_array$S0
IL_0008:  ldc.i4.0    
IL_0009:  ldstr       "a"
IL_000E:  stelem.ref  
IL_000F:  ldloc.1     // VB$LW$t_array$S0
IL_0010:  ldc.i4.1    
IL_0011:  ldstr       "b"
IL_0016:  stelem.ref  
IL_0017:  ldloc.1     // VB$LW$t_array$S0
IL_0018:  ldc.i4.2    
IL_0019:  ldstr       "c"
IL_001E:  stelem.ref  
IL_001F:  ldloc.1     // VB$LW$t_array$S0
IL_0020:  stloc.0     // letters5
IL_0021:  ret    

vs.

Dim letters6(2) As String
letters6(0) = "a"
letters6(1) = "b"
letters6(2) = "c"
IL_0000:  ldc.i4.3    
IL_0001:  newarr      System.String
IL_0006:  stloc.0     // letters6
IL_0007:  ldloc.0     // letters6
IL_0008:  ldc.i4.0    
IL_0009:  ldstr       "a"
IL_000E:  stelem.ref  
IL_000F:  ldloc.0     // letters6
IL_0010:  ldc.i4.1    
IL_0011:  ldstr       "b"
IL_0016:  stelem.ref  
IL_0017:  ldloc.0     // letters6
IL_0018:  ldc.i4.2    
IL_0019:  ldstr       "c"
IL_001E:  stelem.ref  
IL_001F:  ret        

The first version seems to create a temporary variable for the array and copy the reference to the actual variable, which takes two extra instructions. So, it does seem less efficient, but I suppose the nicer code is a worthwhile tradeoff in normal usage.

Upvotes: 2

Related Questions