for (i=0 ; i<=10; i++)
{
..
..
}
i=0;
while(i<=10)
{
..
..
i++;
}
In for and while loop, which one is better, performance wise?
c++for-loopwhile-loop
for (i=0 ; i<=10; i++)
{
..
..
}
i=0;
while(i<=10)
{
..
..
i++;
}
In for and while loop, which one is better, performance wise?
Best Solution
(update) Actually - there is one scenario where the
for
construct is more efficient; looping on an array. The compiler/JIT has optimisations for this scenario as long as you usearr.Length
in the condition:In this very specific case, it skips the bounds checking, as it already knows that it will never be out of bounds. Interestingly, if you "hoist"
arr.Length
to try to optimize it manually, you prevent this from happening:However, with other containers (
List<T>
etc), hoisting is fairly reasonable as a manual micro-optimisation.(end update)
Neither; a for loop is evaluated as a while loop under the hood anyway.
For example 12.3.3.9 of ECMA 334 (definite assignment) dictates that a for loop:
is essentially equivalent (from a Definite assignment perspective (not quite the same as saying "the compiler must generate this IL")) as:
Now, this doesn't mean that the compiler has to do exactly the same thing, but in reality it pretty much does...