does caching array length for a loop condition affect performance?

Is there a big difference between

for (var i = 0, c = data.length; i < c; i++) {

}

And

for (var i = 0; i < data.length; i++) {

}

What is the difference?


In the first code, the length of the array(or array-like collection) is calculated only once and it it cached . So, the length is not recalculated per each iteration.

While in the second code, the length is calculated per iteration .

You can say that caching the length will be slightly faster than recalculating the length. This difference will be very very small that you can neglect this for smaller arrays. But for huge array, the difference could be significant.

Which way to use totally depend on the use case. If the array length is updated inside the loop must use the second code.

for (var i = 0; i < data.length; i++) {
    // Useful when the data length is altered in here
}

每次你计算data.length

for (var i = 0, c = data.length; i < c; i++)  {}
链接地址: http://www.djcxy.com/p/70012.html

上一篇: 用于数组的循环语法的JavaScript

下一篇: 循环条件缓存数组长度是否会影响性能?