Defining Local Variable const vs Class const

C#.NetConstantsJit

C# Problem Overview


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 performance declaring it in the method? If that is true, I think it's more standard to define them at class scope (top of file) to change the value and recompile easier.

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

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

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 :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStealth RabbiView Question on Stackoverflow
Solution 1 - C#jnm2View Answer on Stackoverflow
Solution 2 - C#Neil KnightView Answer on Stackoverflow
Solution 3 - C#user474407View Answer on Stackoverflow
Solution 4 - C#jaltiereView Answer on Stackoverflow
Solution 5 - C#ClintonView Answer on Stackoverflow
Solution 6 - C#Nikola SivkovView Answer on Stackoverflow