Does array length caching for 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?

+4
source share
2 answers

In the first code of an lengtharray (or a massively similar collection) is calculated only once , and it is cached . Thus, the length is not recalculated for each iteration.

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

We can say that caching lengths will be slightly faster than recalculating lengths. This difference will be very small so that you can neglect this for smaller arrays. But for a huge array, the difference can be significant.

. , .

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

, data.length

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

Source: https://habr.com/ru/post/1610102/


All Articles