定义局部variablesconst与类const

如果我使用的只是一个方法中需要的常量,最好在方法范围内还是在类范围内声明const? 在方法中声明它有更好的性能吗? 如果这是真的,我认为在类范围(文件顶部)中定义它们以更改值和重新编译更为简单。

public class Bob { private const int SomeConst = 100; // declare it here? public void MyMethod() { const int SomeConst = 100; // or declare it here? // Do soemthing with SomeConst } } 

将常数转化为类不会带来性能上的好处。 CLR足够聪明,可以将常量识别为常量,所以就性能而言,两者是相等的。 编译为IL时实际发生的事情是,常量的值由编译器作为文字值硬编码到程序中。

换句话说,常量不是引用的内存位置。 它不像一个variables,它更像一个文字。 常量是在您的代码中跨多个位置同步的文字。 所以这取决于你自己 – 尽pipe把整个常量的范围限制在相关的地方是很简单的。

取决于是否要在整个class级中使用它。 顶级声明将在整个课程中使用,而另一个只能在MyMethod 。 无论采用哪种方式,您都不会获得任何性能提升。

这是我做评估场景的一个小基准。

代码:

 using System; using System.Diagnostics; namespace TestVariableScopePerformance { class Program { static void Main(string[] args) { TestClass tc = new TestClass(); Stopwatch sw = new Stopwatch(); sw.Start(); tc.MethodGlobal(); sw.Stop(); Console.WriteLine("Elapsed for MethodGlobal = {0} Minutes {1} Seconds {2} MilliSeconds", sw.Elapsed.Minutes, sw.Elapsed.Seconds, sw.Elapsed.Milliseconds); sw.Reset(); sw.Start(); tc.MethodLocal(); sw.Stop(); Console.WriteLine("Elapsed for MethodLocal = {0} Minutes {1} Seconds {2} MilliSeconds", sw.Elapsed.Minutes, sw.Elapsed.Seconds, sw.Elapsed.Milliseconds); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } class TestClass { const int Const1 = 100; internal void MethodGlobal() { double temp = 0d; for (int i = 0; i < int.MaxValue; i++) { temp = (i * Const1); } } internal void MethodLocal() { const int Const2 = 100; double temp = 0d; for (int i = 0; i < int.MaxValue; i++) { temp = (i * Const2); } } } } 

3次迭代的结果:

 Elapsed for MethodGlobal = 0 Minutes 1 Seconds 285 MilliSeconds Elapsed for MethodLocal = 0 Minutes 1 Seconds 1 MilliSeconds Press any key to continue... Elapsed for MethodGlobal = 0 Minutes 1 Seconds 39 MilliSeconds Elapsed for MethodLocal = 0 Minutes 1 Seconds 274 MilliSeconds Press any key to continue... Elapsed for MethodGlobal = 0 Minutes 1 Seconds 305 MilliSeconds Elapsed for MethodLocal = 0 Minutes 1 Seconds 31 MilliSeconds Press any key to continue... 

我猜测结论@ jnm2答案。

从系统运行相同的代码,并让我们知道结果。

我会把它放在方法本身。 当他们不需要在那里的时候,我并不喜欢那些在范围内存在的变数。

我试着只在我需要的最小范围内定义常量/variables。 在这种情况下,如果仅在MyMethod使用它,请将其留在那里。

这使得它更加清晰,常量/variables适用于何处,并且如果常量被引用到别处,也可以避免检查(即使是编译检查)。

一个例外可能是“昂贵”(时间上)创build/计算,所以我可能希望定义一个实例或静态字段,所以我只需要计算一次。

取决于你想在哪里使用它,如果你打算使用其他方法在类中定义它,如果你打算只用一种方法使用它,请在你要使用的方法中定义它:)