Hacker News new | past | comments | ask | show | jobs | submit login

They're close enough not to matter on most modern browsers - I suspect V8 actually hoists the field access out of the loop when it compiles it (loop-invariant code motion is a really well-understood compiler optimization at this point). I would definitely put this in the premature optimization bucket.

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.


It can only hoist the length out of a for loop if it can prove that the length doesn't change, i.e. the array isn't modified. Otherwise it does have to check it each iteration. This is pretty hard in general since any time you call an external function it could potentially have a reference to the array and modify it.

I suspect the length access is just so fast that the difference between hoisting it out and not is immeasurable.


> for (let elem : arr) { ... }

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.


But

   arr.foreach(elem => { ... });
is still always much slower than a for loop, having the callback call, isn't it?


That very much depends on how good the JIT is, certainly many AOT compilers would understand this pattern and inline the callback, resulting in very similar optimised code.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: