Defining Local Variable const vs Class const

后端 未结 6 1176
时光说笑
时光说笑 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 18:53

    I would put it in the method itself. I'm not a fan of variables that hang around in scope when they don't need to be there.

    0 讨论(0)
  • 2020-12-30 18:57

    I try to only define constants/variables in the most minimal scope that I need them. In this case, if you're using it only within MyMethod, then leave it there.

    It makes it more clear then, where the constant/variable applies and also saves you having to check (even if it's a compile-check) if the constant is referred to elsewhere.

    An exception to this might be something that is 'expensive' (time-wise) to create/calculate, so I might want that defined an instance or static field so I only have to compute it once.

    0 讨论(0)
  • 2020-12-30 18:57

    Depends where do you want to use it , if you are going to use in other methods define it in the class , if you are going to use it only in one method define it in the method you are going to use it :)

    0 讨论(0)
  • 2020-12-30 19:07

    Depends on if you want to use it throughout your class. The top declaration will be usable throughout your class whereas the other will only be available in MyMethod. You won't get any performance boost by doing it either way.

    0 讨论(0)
  • 2020-12-30 19:12

    There is no performance gain in moving the constant into the class. The CLR is smart enough to recognize constants as constant, so as far as performance goes the two are equal. What actually happens when you compile to IL is that the values of the constants are hardcoded into the program by the compiler as literal values.

    In other words, a constant is not a referenced memory location. It is not like a variable, it's more like a literal. A constant is a literal synced across multiple locations in your code. So it's up to you - though it's neater programming to limit the scope of the constant to where it is relevant.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题