在c#中的字段上使用const或readonly修饰符有什么性能优势?

Rus*_*ova 7 c# performance constants readonly

与仅使用私有变量的常规可修改字段相比,使用constreadonly字段是否有任何性能优势.

例如:

public class FooBaar
{
     private string foo = "something";
     private const string baar = "something more"

     public void Baaz()
     {
         //access foo, access baar
     }
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,您可以看到有两个字段:foobaar.这两个都是在课堂之外无法进入的,所以为什么许多人更喜欢在const这里使用,而不仅仅是private.是否const提供任何性能优势?


此问题之前已被社群关闭,因为人们误解了这个问题:" 绩效constreadonly绩效之间有什么区别?" 这里已经回答:const和readonly有什么区别?.
但我的意思是,"通过使用constreadonly不使用其中任何一个,我能获得任何性能优势".

ian*_*lly 15

编译器将优化const以将其内联到您的代码中,readonly不能内联.但是你不能制作所有类型的常量 - 所以在这里你必须使它们只读.

因此,如果您需要在代码中使用常量值,那么首先应该使用const,如果不是,那么readonly就是允许您拥有安全性,而不是性能优势.

举个例子:

public class Example
{
    private const int foo = 5;
    private readonly Dictionary<int, string> bar = new Dictionary<int, string>();

    //.... missing stuff where bar is populated

    public void DoSomething()
    {
       Console.Writeline(bar[foo]);

       // when compiled the above line is replaced with Console.Writeline(bar[5]);
       // because at compile time the compiler can replace foo with 5
       // but it can't do anything inline with bar itself, as it is readonly
       // not a const, so cannot benefit from the optimization
    }
}
Run Code Online (Sandbox Code Playgroud)


spe*_*der -3

在您遇到需要进行此类测量的关键代码之前,我不会过多担心这些构造的性能.它们用于确保代码的正确性,而不是出于性能原因.

  • 非常好的建议,我也不担心表现 - 但不回答问题. (32认同)
  • 这不回答问题,并假设没有编写性能关键代码.绝对不应该是公认的答案. (9认同)
  • 这不是他问的问题,这个问题是否应该在这里也不是问题。如果我们的问题不好,那么我们的答案也一定不好吗?这个答案作为评论会很棒,因为事实就是如此。下面有一个实际的、信息更丰富的答案,已经尘埃落定。 (4认同)