当只使用私有变量时,使用const
或readonly
字段与常规的可修改字段相比是否有性能优势?
public class FooBaar
{
private string foo = "something";
private const string baar = "something more"
public void Baaz()
{
//access foo, access baar
}
}
在上面的示例中,您可以看到有两个字段:foo
和baar
。这两个都是不可访问的类之外,那么为什么许多人更喜欢使用const
在这里,而不是仅仅private
。const
是否提供任何性能优势?
这个问题之前被社区关闭了,因为人们把这个问题误解为"const
和readonly
在性能方面有什么不同?",这里已经回答了:const和readonly的区别是什么?但我真正的意思是,"使用const
或readonly
是否比不使用它们中的任何一个更能获得性能优势"。
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
}
}
在遇到需要进行此类度量的关键代码段之前,我不会太担心这些结构的性能。它们的存在是为了确保代码的正确性,而不是为了性能。