+ 3
why while is faster than for
14 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.
+ 2
A͢J if you test it in code editors, while is actually very faster
+ 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.
+ 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");
+ 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.
+ 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")
+ 1
because it has a low usage on processor unlike "for"
0
sami
Do the same thing there and see which is faster.
0
Maybe because "for" has three arguments messed up together while "while" has discreet 1 argument and i++ is specified separately.
0
after running the tests a few more times, the for loop seems faster on the average.
https://code.sololearn.com/c2lvxDgdOPAk/?ref=app
- 1
Hii
- 1
Apt update on termux