+ 7

Challenge: which loop is faster, "for" or "while" ?

Write code to prove which kind of loop completes a simple task faster. The task should be the same for both loops. The loops should go through the same number of iterations -- as many as you want. Make the test as accurate as possible. Please see our chat below: https://www.sololearn.com/discuss/1133031/?ref=app

11th Mar 2018, 6:23 PM
Eric Zatarack
Eric Zatarack - avatar
5 Réponses
+ 9
My attempt in JS. I'm not sure about the results though, since a lot of people say that the for loop is faster. https://code.sololearn.com/Wnk8xXtMmjfF/?ref=app
11th Mar 2018, 6:57 PM
The Coding Sloth
The Coding Sloth - avatar
+ 8
Thanks guys for your great answers, really good codes and all the up-votes.
11th Mar 2018, 10:59 PM
Eric Zatarack
Eric Zatarack - avatar
+ 5
As @Marcus Sondergaard has said there is no difference, it depends on the compiler, device, operating system and the running processes on the system. This test will show the time each loop takes to complete the same task, some times "for" loop is faster. https://code.sololearn.com/c3fdu52aSez1/?ref=app
11th Mar 2018, 9:41 PM
ƒred
ƒred - avatar
+ 5
In _compiled_ languages there is no difference because the compiler sets the the jump address, compares, jumps if zero... Or similar. However, if the number of loops can be determined constantly, eg: int ii = 4; while (--ii) printf("%d\n", ii); Then the compiler will "unfold" it (the above will become 3 printf() statements). The same for: for (ii = 0; ii < 3; ii++) printf("%d\n", ii); which is also unfolded. Bottom line: compilers are smarter than us and have been for years. From an academic perspective, for is simply a shorthand for while where the number of iterations is _known_.
11th Mar 2018, 11:36 PM
non
+ 4
What is faster would greatly vary depending on the language and the interpreter, compiler or JIT-compiler that's running it. But I'd say that generally there's no difference that one would notice.
11th Mar 2018, 7:18 PM
Marcus Søndergaard
Marcus Søndergaard - avatar