【问题标题】:Is there any performance benefit in using const or readonly modifiers on fields in c#?在 c# 中的字段上使用 const 或 readonly 修饰符是否有任何性能优势?
【发布时间】:2011-10-19 01:49:47
【问题描述】:

与仅使用私有变量的常规可修改字段相比,使用 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 是否比不使用它们获得任何性能优势”

【问题讨论】:

  • 当您厌倦了微优化时,总有纳米优化。
  • 我已经编辑了这个问题,希望大家看看!!
  • @Henk - 我(部分)不同意。当速度成为问题时,人们应该怎么做?问题是关于性能的——答案不应该只是忽略这一点。 Spender 的回答是非常好的建议,但它并不是这个问题的真正答案。
  • 如果是关于性能,唯一明智的答案是:使用分析器来查找问题。不太可能是(缺失的)只读或常量。
  • - 不同的答案 - const yes, readonly no

标签: c# performance constants readonly


【解决方案1】:

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

因此,如果您需要在代码中使用常量值,则应首先尽可能使用 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
    }
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 非常好的建议,我也不担心性能 - 但没有回答问题。
    • 这没有回答问题,并假定没有编写性能关键代码。这绝对不应该是公认的答案。
    • @Daniel :经验告诉我,当问题是“哪个更快,语言特征 X 或语言特征 Y”时,这个人会优先考虑错误的调查。 “性能优势”可以很容易地由 OP 衡量,并且并不真正代表应该在 SO 上提出的问题。最好提醒那些来寻找这个问题的答案的人,他们很有可能以错误的心态看待事物。
    • 这不是他问的问题,问题是否应该在这里不是问题。如果我们有一个不好的问题,我们是否也必须有一个不好的答案?这个答案作为评论会很棒,因为它就是这样。下面有一个实际的,信息量更大的答案,正在收集灰尘。
    • @Daniel:是的。也许您可以 ping OP 以标记另一个答案,然后我很乐意将此答案降级为评论。在那之前,“你不能删除接受的答案”。
    猜你喜欢
    • 2017-03-04
    • 2019-11-11
    • 2021-09-15
    • 2011-08-26
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多