Reputation: 85
Is it performance normal to use constants inside a method in C#?
I mean are there any benefits in using constants as class attributes over using constants as variables inside a method?
If I write
class C {
void f() {
const int i = 0;
}
}
will it be slower than
class C {
const int i = 0;
void f() {}
}
?
Will in the first case variable i
get instantiated every time I call f()
? Or will it be instantiated only once during compilation?
Upvotes: 1
Views: 65
Reputation: 1500065
Will in the first case variable i get instantiated every time I call f()? Or will it be instantiated only once during compilation?
The easiest thing is to try it. For example, compile this code:
using System;
class Test
{
const int ClassConst = 10;
static void PrintLocalConst()
{
const int LocalConst = 10;
Console.WriteLine(LocalConst);
Console.WriteLine(LocalConst);
}
static void PrintClassConst()
{
Console.WriteLine(ClassConst);
Console.WriteLine(ClassConst);
}
}
Both methods are compiled to the same IL:
.method private hidebysig static void PrintLocalConst() cil managed
{
// Code size 18 (0x12)
.maxstack 8
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: call void [mscorlib]System.Console::WriteLine(int32)
IL_0008: nop
IL_0009: ldc.i4.s 10
IL_000b: call void [mscorlib]System.Console::WriteLine(int32)
IL_0010: nop
IL_0011: ret
} // end of method Test::PrintLocalConst
There's no value on the stack for the local constant; instead, every time it's used, the constant value is included directly in the IL - hence ldc.i4.s 10
being used twice.
To that extent, a local const is very, very, very slightly more efficient than a class const, because the class const is still represented in the IL. The local const is effectively completely removed by the compiler. But a few bytes for a constant in the IL representation is incredibly unlikely to ever be significant. (It's not allocated on a per object basis, or per method call.)
Upvotes: 5