Will using 'var' affect performance?

后端 未结 12 1606
南方客
南方客 2020-11-22 14:01

Earlier I asked a question about why I see so many examples use the varkeyword and got the answer that while it is only necessary for anonymous types, that it is used noneth

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 14:44

    For the following method:

       private static void StringVsVarILOutput()
        {
            var string1 = new String(new char[9]);
    
            string string2 = new String(new char[9]);
        }
    

    The IL Output is this:

            {
              .method private hidebysig static void  StringVsVarILOutput() cil managed
              // Code size       28 (0x1c)
              .maxstack  2
              .locals init ([0] string string1,
                       [1] string string2)
              IL_0000:  nop
              IL_0001:  ldc.i4.s   9
              IL_0003:  newarr     [mscorlib]System.Char
              IL_0008:  newobj     instance void [mscorlib]System.String::.ctor(char[])
              IL_000d:  stloc.0
              IL_000e:  ldc.i4.s   9
              IL_0010:  newarr     [mscorlib]System.Char
              IL_0015:  newobj     instance void [mscorlib]System.String::.ctor(char[])
              IL_001a:  stloc.1
              IL_001b:  ret
            } // end of method Program::StringVsVarILOutput
    

提交回复
热议问题