在 C# 中的字段上使用 const 或 readonly 修饰符是否有任何性能优势?

发布于 2024-11-28 04:49:29 字数 748 浏览 1 评论 0原文

仅使用私有变量时,与常规可修改字段相比,使用 const 或 readonly 字段是否有任何性能优势。

例如:

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 和只读?
但我真正的意思是,“与不使用其中任何一个相比,使用 const 或 readonly 是否能获得任何性能优势”。

Is there any performance benefit to using const or readonly fields compared to regular, modifiable fields, when only using private variables.

For example:

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

     public void Baaz()
     {
         //access foo, access baar
     }
}

In the above example you can see there are two fields: foo and baar. Both are unaccessible outside the the class, so how come many people prefer to use const here, instead of just private. Does the const provide any performance benefit?


This question was previously closed by the community, because people misunderstood this question as "What is the difference between const and readonly in terms of performance?", which has been answered here: What is the difference between const and readonly?.
But what I actually mean is, "do I get any performance benefit by using const or readonly over not using any of them".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甩你一脸翔 2024-12-05 04:49:29

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

A const will be optimized by the compiler to be inlined into your code, a readonly cannot be inlined. However you cannot make constants of all types - so here you must make them readonly.

So if you need a constant value in your code, you should first look to use a const if possible, if not then readonly is there to allow you to have the safety, but not the performance benefits.

As an example:

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
    }
}
关于从前 2024-12-05 04:49:29

我也想知道这一点,并且我使用了一个工具来检查使用静态和只读修饰符所产生的 IL 输出。

检查这个示例:

public class C {

    const string test = "stuff";
    private static string test2 = "stuff2";

    public static void M() {
        System.Console.WriteLine(test);
        System.Console.WriteLine(test2);
    }
}

M() 的 IL 输出:

 IL_0000: nop
 IL_0001: ldstr "stuff"
 IL_0006: call void [System.Console]System.Console::WriteLine(string)
 IL_000b: nop
 IL_000c: ldsfld string C::test2
 IL_0011: call void [System.Console]System.Console::WriteLine(string)
 IL_0016: nop
 IL_0017: ret

它不太可能在当前硬件中产生任何性能差异,但似乎常量会将数据携带到 word 当CPU执行指令时,静态引用会携带一个内存指针,这将使CPU检索某个寄存器中的值/L1 缓存/等等。

完整输出:https://gist.github.com/VagnerGon/e8f48a652cc4f234c2ab060a5eeb7d2e

I was wondering the same and I've use a tool to check the resulting IL output from the use of static and read-only modifiers.

Check this example:

public class C {

    const string test = "stuff";
    private static string test2 = "stuff2";

    public static void M() {
        System.Console.WriteLine(test);
        System.Console.WriteLine(test2);
    }
}

And the IL output for M():

 IL_0000: nop
 IL_0001: ldstr "stuff"
 IL_0006: call void [System.Console]System.Console::WriteLine(string)
 IL_000b: nop
 IL_000c: ldsfld string C::test2
 IL_0011: call void [System.Console]System.Console::WriteLine(string)
 IL_0016: nop
 IL_0017: ret

It is unlikely that it will make any performance difference in current hardware, but it seems that constants will carry the data into the word when executing the instruction into the CPU, while the static reference will carry a memory pointer which will make the CPU retrieve the value in some register/L1 cache/so on.

Full output here: https://gist.github.com/VagnerGon/e8f48a652cc4f234c2ab060a5eeb7d2e

笙痞 2024-12-05 04:49:29

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

I wouldn't worry too much about the performance of these constructs until you encounter a critical piece of code that requires you to make such measurements. They're there to ensure correctness of code, not for performance reasons.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文