Rus*_*ova 7 c# performance constants readonly
与仅使用私有变量的常规可修改字段相比,使用const或readonly字段是否有任何性能优势.
例如:
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)
在上面的例子中,您可以看到有两个字段:foo和baar.这两个都是在课堂之外无法进入的,所以为什么许多人更喜欢在const这里使用,而不仅仅是private.是否const提供任何性能优势?
此问题之前已被社群关闭,因为人们误解了这个问题:" 绩效const和readonly绩效之间有什么区别?" 这里已经回答:const和readonly有什么区别?.
但我的意思是,"通过使用const或readonly不使用其中任何一个,我能获得任何性能优势".
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
在您遇到需要进行此类测量的关键代码之前,我不会过多担心这些构造的性能.它们用于确保代码的正确性,而不是出于性能原因.