Why does two small for-loops run faster than a big one ?
(Source/Credits: https://dev.to/nijeesh4all/why-two-small-for-loops-run-faster-than-a-big-one-49pn)
Explain Like I am five Why does two small for loops run faster than one big for loop? s = Date.now(...
title: Why does two small for-loops run faster than a big one ? published: true description: tags: explainlikeimfive, discussion, javascript
Explain Like I am five Why does two small for loops run faster than one big for loop?
``` s = Date.now() for(let i=0;i<1e10;i++) { i + 100 } for(let i=0;i<1e10;i++) { i + 100 } console.log(Date.now() - s) // => 37s
s = Date.now() for(let i=0;i<2e10;i++) { i + 100 } console.log(Date.now() - s) // => 38s
```
Especially for language like JS which is not multi-threaded
Comments section
nijeesh4all Author
•May 1, 2024
i ran this in my server for more than 800 times these are my results pastebin.com/bRqku0zJ
dati
•May 1, 2024
This has nothing to do with JIT compiler, loops, multi-threading or BigInt. If this was a some quiz question it would test:
-Understating that every number in js implicitly is floating point number
-Knowing how floating point addition works and that (unlike addition of integers) it takes multiple hw level operations
Addition_and_subtraction
To make this test fair for both one loop variant and two loops variant:
```
s = Date.now() for(let i=0;i<1e10;i++) { i + 100 } for(let i=1e10;i<2e10;i++) { i + 100 } console.log(Date.now() - s)
s = Date.now() for(let i=0;i<2e10;i++) { i + 100 } console.log(Date.now() - s)
```
Enter fullscreen mode
Exit fullscreen mode
Now both variants work with exact same numbers and perform exact same floating point operations (time diff is consistently <20ms on my machine now, where it was 500-1500ms before)
TLDR: floating point
nijeesh4all Author
•May 1, 2024
Thanks man, it took me a while to understand. I think this might be the best answer.
vlasales
•May 1, 2024
BigInt is slower.