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

时间:2011-08-03 12:24:13

标签: 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
     }
}

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


此问题之前已被社群关闭,因为人们误解了这个问题constreadonly在性能方面有什么区别?”,已在此处回答:What is the difference between const and readonly?
但实际上我的意思是,“使用constreadonly而不是使用其中任何一个”,我是否可以获得任何性能优势。

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:5)

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