## DEV Community is a community of 753,853 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Why does two small for-loops run faster than a big one ?

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

## Discussion (6) 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

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)
```

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 graciano codes

oh, thanks! Nijeesh Joshy • Edited on

Thanks man, it took me a while to understand. I think this might be the best answer. graciano codes • Edited on

Javascript (both on the browser and node) is run by a JIT (just in time) compiler. This means that the "translation" of your code to machine code happens at the time of execution. Since it's not exactly an interpreter, this translation doesn't happen one line at a time. But since it's not a regular compiler it also doesn't happen everything at once (with optimizations) before execution. It's somewhere in the middle.

So a lot of things can happen when this JIT compiler is "reading" your code. You may switch tabs. Your SO may be updating. To do a proper benchmark, you would have to run this multiple times and make sure the conditions on your machine are always the same. I'm not sure if those results you showed would be true. 