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

twitter logo github logo 惻1 min read

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

twitter logo DISCUSS (6)
markdown guide
 

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)

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

 
 

Thanks man, it took me a while to understand. I think this might be the best answer.

 

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.

For more, read this article

 

i ran this in my server for more than 800 times these are my results pastebin.com/bRqku0zJ

 
Classic DEV Post from Jan 22

Self Care for Developers

Self care is a hot topic these days, and Iā€™m not just talking about face masks. There is a growing movement that underscores the importance of taking time to take care of yourself (in addition to all the other things that you already take time for). You can prevent problems down the road by taking proactive steps to ensure your health and happiness.

Nijeesh Joshy profile image
Some one Who Love to Code ,Create and Experiment with Everything

Hey there reader...

Do you prefer sans serif over serif?

You can change your font preferences in the "misc" section of your settings. ā¤ļø