Is for loop faster or while loop faster..

Among these 3 versions of loops which one is faster…

for(i=0;in;i++)
while(n--)
for(;n--;)

their semantic is equivalent. if your compiler is smart enough, the cpu instructions generated are exactly the same. so none of them is faster than the other.

4 Likes

Whatever may be the form of loop, the test condition will take same time. Since, you have skipped initialisation condition in last format, it won’t be done but testing will be done. You can check the assembly language code using clang compiler in Linux by passing -S flag at the time of compiling. For loop sometimes takes 1-2 more instructions but that doesn’t matters much and is dependant on the processor also that which instruction set is being used.

1 Like

Check this link out. I hope it explains all :slight_smile:

2 Likes

There is not much difference in both , so one might turn out to be faster than other by not more than a few milli seconds .
And Yes the above mentioned link explains the same . :slight_smile:

8 Likes

just count the operations

The major difference is just in the syntax.Run time will not differ much.:slight_smile:

4 Likes
//