在c#中对字段使用const或只读修饰符有什么性能上的好处吗?



当只使用私有变量时,使用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在性能方面有什么不同?",这里已经回答了:const和readonly的区别是什么?但我真正的意思是,"使用constreadonly是否比不使用它们中的任何一个更能获得性能优势"

const将被编译器优化为内联到你的代码中,只读不能内联。但是,您不能将所有类型的常量都设置为常量——因此这里必须将它们设置为只读。

所以,如果你的代码中需要一个常量值,你应该首先考虑使用const,如果可能的话,如果不是,只读可以让你有安全,但不是性能上的好处。

例如:

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
    }
}

在遇到需要进行此类度量的关键代码段之前,我不会太担心这些结构的性能。它们的存在是为了确保代码的正确性,而不是为了性能。

最新更新