by nostrademons · 6y ago · 0 comments
It doesn't really matter nowadays anyway, because now I write my for-each loops like:
for (let elem : arr) { ... }
or arr.foreach(elem => { ... });
(Well, technically now I write Android & C++ code and do leadership/communication stuff, but I brushed up on my ES6 before getting the most recent job.) for (let elem of arr) {}
is actually quite a bit slower than for (let i = 0; i < arr.length; i++) {}
because the people who built the JS spec decided that there should be a brand new heap object created every iteration. At the time, there was thought that escape analysis would let them optimize away this object, but from what I can tell, ten years later, engines are really bad at it. Escape analysis is a heuristic, and it needs to be conservative.And yes, this isn't a micro-benchmark. At least in my application, performance is mostly bounded from GC pauses and collection, not slow code execution. Anything to reduce your GC pressure is going to be a good improvement... but note that modern frameworks like React are already basically trashing your heap, so changing out your loops in an already GC-heavy codebase won't really do much.
I suspect the length access is just so fast that the difference between hoisting it out and not is immeasurable.
Do you mean:
for (let elem of arr) { ... }
Unless this is a joke about writing in Java & C++ (for which the colon syntax is valid) instead of javascript. arr.foreach(elem => { ... });
is still always much slower than a for loop, having the callback call, isn't it?