56

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

6 Answers 6

57

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.

1
  • 5
    Agree with "it's neater programming to limit the scope of the const", unfortunately most C# programmers still seem to automatically make a const global to the class or even the project even when its only used locally in one method
    – bytedev
    May 8, 2018 at 16:17
10

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.

2
  • Understood. I tried to indicate that in my first sentence. The const is only needed within the scope of MyMethod() Jun 16, 2011 at 13:58
  • 1
    @Stealth Rabbi: Then declare it in MyMethod :o) Jun 16, 2011 at 13:58
7

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.

4
  • 1
    What you did is good. It's also informative to reverse engineer the IL and see exactly what's going on behind the scenes. In this case constants get hardcoded in as literal values. They aren't like variables.
    – jnm2
    Jun 16, 2011 at 15:01
  • 1
    My results on an x86 box. Looks like the global const is slightly slower, but reversing the calls (local before global) shows Local taking more time. Elapsed for MethodGlobal = 0 Minutes 8 Seconds 593 MilliSeconds Elapsed for MethodLocal = 0 Minutes 8 Seconds 501 MilliSeconds Press any key to continue... Elapsed for MethodGlobal = 0 Minutes 8 Seconds 571 MilliSeconds Elapsed for MethodLocal = 0 Minutes 8 Seconds 494 MilliSeconds Press any key to continue... PS - Yikes, I have a lot of crap ware on my box. Jun 17, 2011 at 16:55
  • Ugh, sorry about the nasty formatting. I don't think I have a choice for comments. Jun 17, 2011 at 16:59
  • So the difference is ~1%, i.e. no difference (especially when you take into account a lot of different things could have caused that ~1% difference on your machine).
    – bytedev
    May 8, 2018 at 16:23
3

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.

1
  • A const isnt actually a variable. Its more of a placeholder for a literal. I think this might be where some of the confusion comes from :-).
    – bytedev
    May 8, 2018 at 16:26
3

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.

1

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

2
  • But is there a performance benefit of defining it within the method scope? Jun 16, 2011 at 13:59
  • 2
    @stealth-rabbi: There is no performance benefit either way. (See my answer.)
    – jnm2
    Jun 16, 2011 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.