Which JS loop is fast?

which-js-loop-is-fast?

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 started…

I am going to perform this test at 10 billion value for the loops

For loop –

let count = 0;
let start = new Date().getTime();
for(let i = 0; i<10000000000;i++){
  count += i
}
let end = new Date().getTime();

console.log((end - start)/1000)

OUTPUT –

I performed it 10 times and got the result in seconds

22.01
14.56
14.49
14.93
15.03
15.10
15.30
15.11
16.34
15.92

While loop –

let count = 0;
let start = new Date().getTime();
let i = 0;
while (i < 10000000000){
    count += i;
    i++;
}
let end = new Date().getTime();

console.log((end - start)/1000)

OUTPUT –

I performed it 10 times and got the result in seconds

21.20
14.69
14.42
15.64
16.93
15.79
16.40
16.09
19.05
18.27

do-while loop –

let count = 0;
let start = new Date().getTime();
let i = 0;
do{
    count += i;
    i++
} while (i < 10000000000)
let end = new Date().getTime();

console.log((end - start)/1000)

OUTPUT –

I performed it 10 times and got the result in seconds

22.36
14.83
15.36
14.82
15.48
18.17
22.48
17.08
18.64
18.11

Averages –

  • For loop – 15.87
  • While loop – 17.14
  • Do-while loop – 17.73

From my test results , For loop is slightly better than while and do-while but i am saying this with test results and i can be wrong as well

NOTE – 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.

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ –> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl

Total
1
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
what-is-an-example-of-how-an-application-can-anticipate-user-behavior?

What is an example of how an application can anticipate user behavior?

Next Post
[pt-br]-functional-interfaces,-a-fundacao-para-a-programacao-funcional-com-java

[PT-BR] Functional Interfaces, a fundação para a programação funcional com Java

Related Posts