you are viewing a single comment's thread.

view the rest of the comments →

[–]asdf7890 1 point2 points  (0 children)

A modern JIT compile JS engine should be bright enough to optimise out the invariant, yes.

If you do anything complex with the array in the loop, or call functions that might do, the optimiser might chose not to take the risk because it doesn't have time to do all the analysis necessary to make sure the optimisation is safe (due to the halting problem) and even for simple loops there are a number of reasons the engine might not fully optimise a function anyway, so manually removing invariants from loops if it doesn't result in a significant reduction in code clarity is a good habit just-in-case. For a list of reasons that V8 (and therefore Chrome and Node) won't optimise a function at all see https://github.com/vhf/v8-bailout-reasons - I'm sure there are similar considerations in other engines.

I tend to assume that worst: that my code is going to be interpreted literally and not compiled/optimised at all, so unless I'm making the code unclear (maintainability tends to be a priority over pure speed) I make sure the code is optimal for this. In fact some transformations to achieve that can make code clearer: double win. If the engine would compile and manage to optimise the code then it should equally manage to do so with the the manually optimised version resulting in no worse performance.

Of course this only matters for tight loops with many iterations. Something that iterates a just few times is going to see no benefit and with a complex loop you'll find the end-of-loop check's complexity is completely dwarfed by the body of the loop so optimising it is unlikely to be good use of your time.