正在更快地访问只读成员



尝试读取私有"只读"实例成员变量与私有实例成员变量时,速度是否有差异?

更新

这个问题的目的是为了更好地理解和达到理论目的。

没有性能差异。不过,更改为"const"会获得一些性能。所有这些都在这篇漂亮的文章中精辟地描述了出来;

http://www.dotnetperls.com/readonly

假设您有以下代码:

void Main()
{
    Test t = new Test();
    t.Check();
}
public class Test
{
    private readonly int  num = 10;
    private int num1 = 50;
    public void Check()
    {
        int a = num1;
        int b = num;
    }
}

现在生成的MSIL代码是以下

IL_0001:  newobj      UserQuery+Test..ctor
IL_0006:  stloc.0     
IL_0007:  ldloc.0     
IL_0008:  callvirt    UserQuery+Test.Check
Test.Check:
IL_0000:  nop         
IL_0001:  ldarg.0     
IL_0002:  ldfld       UserQuery+Test.num1
IL_0007:  stloc.0     
IL_0008:  ldarg.0     
IL_0009:  ldfld       UserQuery+Test.num
IL_000E:  stloc.1     
IL_000F:  ret         
Test..ctor:
IL_0000:  ldarg.0     
IL_0001:  ldc.i4.s    0A 
IL_0003:  stfld       UserQuery+Test.num
IL_0008:  ldarg.0     
IL_0009:  ldc.i4.s    32 
IL_000B:  stfld       UserQuery+Test.num1
IL_0010:  ldarg.0     
IL_0011:  call        System.Object..ctor
IL_0016:  nop         
IL_0017:  ret         

所以我看到readonly是一个特定于语言的关键字,用于表达编程概念
编译器在构建代码时,强制执行只读规则
从生成代码的角度来看,没有什么区别

最新更新