定义局部变量const与类const

问题描述 投票:48回答:6

如果我使用的是仅在方法中需要的常量,那么最好在方法范围内或类范围内声明const?在该方法中是否有更好的性能声明?如果是这样,我认为在类范围(文件顶部)定义它们以更改值并更容易重新编译是更标准的方法。

public class Bob
{
   private const int SomeConst = 100; // declare it here?
   public void MyMethod()
   {
      const int SomeConst = 100; // or declare it here?
      // Do something with SomeConst
   }
}
c# .net const jit
6个回答
48
投票
换句话说,常量不是引用的存储位置。它不像变量,更像文字。常量是在代码中多个位置同步的文字。因此,这取决于您-尽管更精巧的编程是将常量的范围限制在相关的范围内。

9
投票

7
投票
代码:

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答案。

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

3
投票

3
投票

1
投票
© www.soinside.com 2019 - 2024. All rights reserved.