Reputation: 1481
i ran this code on the my server an i noticed there is a performance difference between running two separate loops vs single for-loop can someone explain why ?
for(let k=0;k<100000000;k++) {
let s = Date.now();
for(let i=0;i<1e9;i++) { i + 100 }
for(let i=0;i<1e9;i++) { i + 100 }
let s1 = Date.now() - s;
s = Date.now();
for(let i=0;i<2e9;i++) { i + 100 }
let s2 = Date.now() - s;
console.log(s1, s2 , s1 - s2)
}
these are my results in json: https://pastebin.com/bRqku0zJ
Upvotes: 2
Views: 78
Reputation: 1481
I posted the question in dev2 also. Thanks to da-ti. https://dev.to/dati/comment/eii1
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
Upvotes: 2