why while is faster than for | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
2nd Apr 2022, 12:36 PM
sami
sami - avatar
12 Answers
+ 4
Loops' performance is more likely to get affected by the complexity of the calculation inside its body, rather than the kind of loop.
2nd Apr 2022, 3:13 PM
Ipang
+ 2
A͢J if you test it in code editors, while is actually very faster
2nd Apr 2022, 12:51 PM
sami
sami - avatar
+ 2
Maybe for while we used let to create a varible it saves varible to local memory and after while execution deletes varible. But for for loop it doesn’t deletes varible.
3rd Apr 2022, 4:20 PM
Daniil Pivovarov
Daniil Pivovarov - avatar
+ 1
sami Now Just change position of loops and see which is faster // console.time("while"); let i = 0; while(i < 200000){ i++; } console.timeEnd("while"); // console.time("for"); let j = 0; for(j;j< 200000;j++){ } console.timeEnd("for");
2nd Apr 2022, 12:47 PM
A͢J
A͢J - avatar
+ 1
a quick google search also supports the idea of the for loop being faster. But why the obsession with speed? Real world codes are not just simple loops and a lot of things will slow down your program. Readability and maintainability would rank higher up in my list.
3rd Apr 2022, 6:23 AM
Bob_Li
Bob_Li - avatar
+ 1
In this 2nd for loop is faster while 1st one is slowest // console.time("for"); let j = 0; for(;j< 200000;j++){ } console.timeEnd("for"); // console.time("while"); let i = 0; while(i < 200000){ i++; } console.timeEnd("while"); console.time("for2"); let k = 0; for(;k< 200000;k++){ } console.timeEnd("for2")
3rd Apr 2022, 9:19 PM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
+ 1
because it has a low usage on processor unlike "for"
4th Apr 2022, 2:15 AM
Eslam El-Dewany
Eslam El-Dewany - avatar
0
sami Do the same thing there and see which is faster.
2nd Apr 2022, 1:07 PM
A͢J
A͢J - avatar
0
Maybe because "for" has three arguments messed up together while "while" has discreet 1 argument and i++ is specified separately.
4th Apr 2022, 10:33 AM
Nikunj Vashishtha
Nikunj Vashishtha - avatar
0
after running the tests a few more times, the for loop seems faster on the average. https://code.sololearn.com/c2lvxDgdOPAk/?ref=app
4th Apr 2022, 10:54 AM
Bob_Li
Bob_Li - avatar
- 1
Hii
4th Apr 2022, 11:01 AM
Akash Das
- 1
Apt update on termux
4th Apr 2022, 11:02 AM
Akash Das