定义局部变量const与类const

Ste*_*bbi 47 .net c# jit 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
   }
}
Run Code Online (Sandbox Code Playgroud)

jnm*_*nm2 47

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

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

  • 同意“限制 const 的范围是一种更简洁的编程”,不幸的是,大多数 C# 程序员似乎仍然自动将 const 设为类甚至项目的全局变量,即使它仅在一种方法中本地使用 (3认同)

Nei*_*ght 9

取决于您是否想在整个班级使用它.顶级声明将在整个课程中使用,而另一个声明仅适用于MyMethod.无论哪种方式,都不会有任何性能提升.


小智 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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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...
Run Code Online (Sandbox Code Playgroud)

我猜观察结束了@ jnm2的回答.

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