I know that in browser it is more optimal to write a for loop along the lines of
for(var i=0, l=arr.length; i<l; i++){ }
instead of
for(var i=0; i<arr.length; i++){ }
But is this true in NodeJS or does the V8 engine optimize it?
I know in ecma-262 5.1 sec-15.4 array length is defined as such:
The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant.
Thus if the length doesn't change the only reason this method would be slower is because you have to access the property. What I'm looking for is a reasonable example/ explanation that would show whether or not the V8 engine (which is used in NodeJS) suffers in performance when accessing this property.
If arr
is a pure local variable and the loop doesn't touch it in any way, then yes. However even if the optimization fails, loading the same field over and over again doesn't really cost anything due to CPU cache.
I would always use the first if applicable because it informs both the interpreter and any future reader of the code that the loop does not modify the length of the array.
Even if it's not faster (although http://jsperf.com/array-length-vs-cached suggests it actually is) it's simply good practise to factor constant expressions from outside of a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With