According to this blog, this code
for( i =0; i<10; i++)
is slower than this code
for(i=10; i--; )
because
It is faster to test if something is equal to zero than to compare two different numbers.
Is this true? Why?
According to this blog, this code
for( i =0; i<10; i++)
is slower than this code
for(i=10; i--; )
because
It is faster to test if something is equal to zero than to compare two different numbers.
Is this true? Why?
The blog is correct, however, from my experience performance is more complex than changing a few small tweaks.
The important element ain't the order of looping. You would get the same effect when going from -10 to 0. The relevant element here is the comparison with 0. CPUs have a dedicated instruction to compare with 0, while comparison with any other number needs to use a generic comparison.
So for the looping, yes, it will be faster. Though, as mentioned before, a lot more is at play. Compiler optimizations line loop unrolling could remove the complete loop. Almost any operation is more expensive than the looping itself and algorithmic changes can save a lot of time.
For more details on comparison with zero, you can start in following thread: Is comparing to zero faster than comparing to any other number?
its know that this loop last position is 0 so can't check condition. so its direct i-1 and then print
int main()
{
int i;
for( i =10; i--;)
{
cout<<i;
}
return 0;
}