Possible Duplicate:
Difference between declaring variables before or in loop?
I always wondered, is it faster to do like this:
int i;
for (i=0;i<...)
for (i=0;i<...)
for (i=0;i<...)
for (i=0;i<...)
or
for (int i=0;i<...)
for (int i=0;i<...)
for (int i=0;i<...)
for (int i=0;i<...)
Meaning, if i have multiple for loops in one function, does it work faster if i declare loop iteration variable once and use it multiple times, or declare it inside each for loop?
The IL generated will be (for release build) pretty much identical for both approaches.
Consider this code:
This generates the following IL for a release build, which I have placed side-by-side for easier comparison:
This makes it pretty clear that you should choose the version where ‘i’ is local to the loop, because that’s better practice.
However, the version with the loop counter declared outside the loops will be faster by the amount of time needed to initialise an int to zero – pretty much negligible.