Reputation: 15372
Is it more efficient to declare a variable with another variable's length before doing a for-loop or should the length be calculated within the loop.
I'm certain the answer depends on how big the array is that the length is being calculated it on. I just always see
for ( var i = 1; i <= theVar.length; i++ ) {
}
but then i was told that it is less resource intensive to do
var theVarLen = theVar.length
for ( var i = 1; i <= theVarLen; i++ ) {
}
as it avoids the recalculation of the length every iteration.
Or does it depend on specific circumstances so much it's impossible to make a categorical decree?
Or, does it not really matter at all..?
Thanks a bunch!
Upvotes: 2
Views: 2289
Reputation: 298196
Well, let's find out. I've created a test here that you can run: http://jsperf.com/loop-length-caching
Browsers seem to store the length of the array once it is created (and possibly modified), so there are no huge speed benefits from storing the length in a variable. The only real factor (in this case) is the difference in speed between accessing an object's property and accessing a variable.
Upvotes: 4
Reputation: 2650
Arguably, it's one less pointer to dereference internally, but I have never, ever seen it done the second way in real code. I believe one would have a hard time justifying any performance you might gain.
Upvotes: 1