ninjaPixel
ninjaPixel

Reputation: 6382

Efficiency of calling array.length in javascript

Most looping examples I see in javascript use the array.length property in the for loop itself, like so:

var numbers = [1,2,3,4,5];
for (var i = 0; i < numbers.length; i++) {
  // do something
}

However, sometimes I see the array.length property being written to a variable, and then the variable value is used in the loop, instead:

var numbers = [1,2,3,4,5];
var len = numbers.length;
for (var i = 0; i < len; i++) {
  // do something
}

Coming from a C# background, I've never had to worry about this. However, in Javascript is the second method more efficient and why?

Upvotes: 2

Views: 109

Answers (1)

Isaiah Taylor
Isaiah Taylor

Reputation: 627

The second is more efficient because it does not have to make an operation on anything. In the first, it just has to reference a data cell each time.

Upvotes: 1

Related Questions