定义局部变量const与类const

时间:2011-06-16 13:55:14

标签: c# .net const jit

如果我使用仅在方法的常量,那么最好在方法范围内或类范围内声明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
   }
}

6 个答案:

答案 0 :(得分:46)

将常量移动到类中没有性能提升。 CLR非常智能,可以将常量识别为常量,因此就性能而言,两者是相等的。编译为IL时实际发生的事情是编译器将常量的值硬编码到程序中作为文字值。

换句话说,常量不是引用的内存位置。它不像变量,更像是文字。常量是代码中多个位置同步的文字。所以这取决于你 - 尽管它是更简洁的编程,将常量的范围限制在相关的位置。

答案 1 :(得分:8)

取决于您是否想在整个班级使用它。顶部声明将在整个班级中使用,而另一个声明仅在MyMethod中可用。无论如何都不会有任何性能提升。

答案 2 :(得分:6)

这是我为评估方案所做的一个小基准测试;

代码:

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)

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

答案 4 :(得分:3)

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

它使得更清楚,常量/变量适用的地方,并且还可以节省您必须检查(即使它是编译检查)如果常量被引用到别处。

对此的例外可能是创建/计算“昂贵”(按时间),因此我可能希望定义一个实例或静态字段,因此我只需要计算一次。

答案 5 :(得分:1)

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