DEV Community

Cover image for Which JS loop is fast?

Which JS loop is fast?

Shubham Tiwari on August 08, 2022

Hello Guys Today i will discuss which loop among "for","while" and "do-while" is faster? I am comparing only these 3 loops in this post. Let's get...
Collapse
 
smac89 profile image
smac89

Next time you want to do timings in JS, instead of manually calculating the time, just use console.time(label) and it's companion console.timeEnd(label).

See docs: developer.mozilla.org/en-US/docs/W...

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Thank you i will use it

Collapse
 
rouilj profile image
John P. Rouillard

Which JS interpreter are you using? Is it possible it's running a JIT optimize step as part of the first run that is reflected in the
subsequent runs?

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

I am using node js for running these

Collapse
 
rouilj profile image
John P. Rouillard

Ok, so V8. So suspect the answer to your question:

While running the loop first time in every case the time
taken is higher compared to other 9 test case, please
mention the reason in the comment section if you know that.

is probably the JIT compiler/optimizer:

blog.logrocket.com/how-javascript-...

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Thank i will read this

Collapse
 
suryakant profile image
Suryakant Patil

Hey, Can you test the below For loop? I guess it will give you slightly better performance.

let i=0;
for(; i<10000000000;i++){
  count += i
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

The code is not correct can you please write it correctly

Collapse
 
fjones profile image
FJones • Edited

I'm not sure where you're struggling. The error message is quite telling, in that all that's missing is:

- let i=0;
+ let i=0, count;
Enter fullscreen mode Exit fullscreen mode

Then the snippet runs. Though my quick look over it seems to make it benchmark slower than the for-scoped version, which is a bit surprising.

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Yeah got it

Collapse
 
andrewbaisden profile image
Andrew Baisden

Speed and performance really become a serious requirement when you are trying to find the best data structure for your application. Especially when it has a lot of users.

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Yes it is and i performed this test because I wanted to see that all these loops are equal or have some sort of difference