Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS for loop optimization

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.

like image 396
Sleep Deprived Bulbasaur Avatar asked Dec 22 '14 14:12

Sleep Deprived Bulbasaur


2 Answers

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.

like image 177
Esailija Avatar answered Oct 06 '22 00:10

Esailija


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.

like image 45
Alnitak Avatar answered Oct 06 '22 00:10

Alnitak