如果我使用的是仅在方法中需要的常量,那么最好在方法范围内或类范围内声明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
}
}
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答案。
请从您的系统中运行相同的代码,并让我们知道结果。