set length to variable or calculate length within loop statment

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!


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.


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.

链接地址: http://www.djcxy.com/p/70006.html

上一篇: 数组的长度是否缓存?

下一篇: 将长度设置为变量或计算循环统计中的长度