nunu
nunu

Reputation: 3252

What gives you the better perfomance? C# : Const Vs Normal fields -in FOR loop fields declaration

I would like to know which gives us a better performs on both the ways as given below:

1. Way 1

for(int i = 0; i < 10; i++)
{
   // do something in loop
}

2. Way 2

for(int i = Constants.Zero; i < Constants.Ten; i++)
{
    // do something in loop
}
private const int Zero = 0; 

private const int Ten = 10;

Basically I want to know that Can we increase the application performance if we use Constants in for loop variable declaration as mentioned above?

Thanks in advance !

Upvotes: 0

Views: 129

Answers (2)

Tigran
Tigran

Reputation: 62276

There is no any performance benefit here, as variable declared in that way will end up into injected constants, like in your first case. So they are become basically the same.

//code 1
for(int i = 0; i < 10; i++)
{
     Console.WriteLine("Hello");
}

//IL 1

IL_0001:  ldc.i4.0    
IL_0002:  stloc.0     
IL_0003:  br.s        IL_0016
IL_0005:  nop         
IL_0006:  ldstr       "Hello"
IL_000B:  call        System.Console.WriteLine
IL_0010:  nop         
IL_0011:  nop         
IL_0012:  ldloc.0     
IL_0013:  ldc.i4.1    
IL_0014:  add         
IL_0015:  stloc.0     
IL_0016:  ldloc.0     
IL_0017:  ldc.i4.s    0A 
IL_0019:  clt         
IL_001B:  stloc.1     
IL_001C:  ldloc.1     
IL_001D:  brtrue.s    IL_0005

//code 2
for(int i = Constants.Zero; i < Constants.Ten; i++)
{
    Console.WriteLine("Hello");
}

//IL 2
IL_0001:  ldsfld      UserQuery+Constants.Zero
IL_0006:  stloc.0     
IL_0007:  br.s        IL_001A
IL_0009:  nop         
IL_000A:  ldstr       "Hello"
IL_000F:  call        System.Console.WriteLine
IL_0014:  nop         
IL_0015:  nop         
IL_0016:  ldloc.0     
IL_0017:  ldc.i4.1    
IL_0018:  add         
IL_0019:  stloc.0     
IL_001A:  ldloc.0     
IL_001B:  ldsfld      UserQuery+Constants.Ten
IL_0020:  clt         
IL_0022:  stloc.1     
IL_0023:  ldloc.1     
IL_0024:  brtrue.s    IL_0009

In second case I used a static class to create constants.

Upvotes: 4

LukeH
LukeH

Reputation: 269498

There is no performance difference. The compiled for loop will be exactly the same in both cases.

The constants are "burned into" the compiled code, just as if you'd used literal values.

(And I'm assuming that this is just a toy example: otherwise why would you want to replace perfectly good, universally recognised symbols -- 0, 10, etc -- with your own versions that aren't widely known?)

Upvotes: 3

Related Questions