UPDATE:
Many of the old tricks in these answers are great for interpreted JS in older browsers.
In any modern JS implementation, including all modern browsers, Node, and the latest mobile web views, the built-in functions can be actually cached by JIT (JS compiler), which makes Each a much faster option for iterating the array, as a rule. Previously, it was the other way around, when a simple call to a function repeatedly required an extension / break process, which could seriously reduce the performance of a non-trivial cycle.
For maximum performance, I would avoid referring to everything that was not passed as an argument or defined inside the function itself if you do not need it. I am not 100% sure, but I could understand why this is possible.
Getter values ββthat are associated with any kind of search process, such as array length or DOM node properties, are probably also best cached for a variable.
But beyond that, I would just try to let the basic principle avoid work by directing your efforts. A good example of this is to pre-compute things that don't need to be recounted in a loop, or to cache the result of a query selector in var, rather than rummaging through the DOM. Trying too hard to use JIT behavior is likely to become rather cryptic and unlikely to linger over time or in all JITs.
OLD RESPONSE:
Ok, forget the wall of text. Points:
var i = someArray.length; //length is cached someArray.reverse(); //include this only if iterating in 0-(length-1) order is important while(i--){ //run a test statement on someArray[i]; }
the length is cached and immediately converted to an index
The advantage of reuse in JS AFAIK is to avoid a logical operator with two operands. In this case, we simply evaluate the number. This is true or equal to zero and false.
I also find it elegant.
Erik reppen
source share