4 ms·
”what if rather than iterating thru the array from the 0th element to the length of the array, you instead started from the last element and iterated backwards,
by Someone 7y ago
”what if rather than iterating thru the array from the 0th element to the length of the array, you instead started from the last element and iterated backwards, until you hit zero?”
That used to be common in assembly, as it leads to smaller and faster code on many systems.
See https://stackoverflow.com/questions/2823043/is-it-faster-to-count-down-than-it-is-to-count-up https://stackoverflow.com/questions/2823043/is-it-faster-to-..., which also shows how times have changed, with many answers calling this premature optimization.
- masklinn 7y agoWas also common in javascript a few years ago when the runtimes were more simplistic than they are now. Iterating from the tail also made the terminal condition a comparison to 0, which IIRC was faster in at least one browser. The gains were mostly masturbatory of course, the overhead of the iteration loop is not going to matter much when you have 5 method calls in the body.
- Sahhaese 7y agoIterating from the tail has other advantages, such as if you want to remove items from the list. With negative iteration you don't need to do any special handling. But that is an optimisation for development time rather than run-time, I'd imagine multiple in-place removals is not so efficient.