Reputation: 37751
phew! That was a long title.
I'm reading WROX' book on Professional JavaScript for web developers and I came across this sample code, and I was just wondering if that was best practice:
function convertToArray(nodes) {
array = new Array();
for (var i=0, len=nodes.length; i < len; i++) {
array.push(nodes[i]);
}
return array;
}
The thing that's got me scratching my head is the "len=nodes.length". Am I wrong in thinking that the first sentence in a for-loop is only run once? Is there a reason you'd want to set a variable (len) to the length of the nodeList before running through it? Would you do that to a normal array as well?
Thanks
Upvotes: 2
Views: 919
Reputation: 169593
While we're discussing micro-optimizations, the following should be even faster:
function convertToArray(nodes) {
var i = nodes.length,
array = new Array(i); // potentially faster than `array = []`
// -- see comments
while(i--)
array[i] = nodes[i];
return array;
}
It needs one less local variable, uses a while
and not a for
loop and uses array assignment instead of the function call push()
.
Also, because we're counting down we pre-allocate the array's slots, the array's length doesn't have to be changed each iteration step, but only on the first one.
Upvotes: 3
Reputation: 106920
That is for performance reasons. A local variable is faster for several reasons:
nodes
is an array, then .length
is a magic property that may take a bit longer to retrieve than a member variable.nodes
is an ActiveX object, then .length
might result in a method call into the object, so that's the most expensive operation of all.Upvotes: 6