Defining Local Variable const vs Class const

后端 未结 6 1175
时光说笑
时光说笑 2020-12-30 18:12

If I am using a constant that is needed only in a method, is it best to declare the const within the method scope, or in the class scope? Is there better pe

6条回答
  •  借酒劲吻你
    2020-12-30 19:13

    Here is a small benchmark I did to evaluate the scenarios;

    The code:

    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);
                }
            }
        }
    }
    

    The results of 3 iterations:

    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...
    

    I guess the observation concludes @jnm2 answer.

    Do run the same code from your system and let us know the result.

提交回复
热议问题