NodeJS for loop optimization
I know it is more optimal in the browser to write a for loop along the lines
for(var i=0, l=arr.length; i<l; i++){ }
instead
for(var i=0; i<arr.length; i++){ }
But is this true in NodeJS, or is the V8 engine optimizing it?
I know in ecma-262 5.1 sec-15.4 the length of the array is defined as such:
The length property is numerically greater than the name of each property whose name is an array index; when a property of an Array object is created or changed, the other properties are adjusted as needed to maintain this invariant.
So, if the length doesn't change, the only reason this method will be slower is because you need to access the property. What I'm looking for is a sane example / explanation that shows if the V8 engine (which is used in NodeJS) has any performance impact on accessing this property.
source to share
I would always use the former, if applicable, because it informs both the interpreter and any future reader of the code that the loop does not change 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 just good practice to express constant expressions from outside the loop.
source to share
The challenge is calculating the length. In this example, the for(var i=0; i<arr.length; i++){ }
operator arr.length
will be evaluated at each iteration of the loop. But the s for(var i=0, l=arr.length; i<l; i++){ }
value will be accepted without any computation. Just getting the value is faster than calculating the length of the array.
Obtaining the length cannot be optimized by any compiler because it could be changed. So he calculated every iteration.
source to share