4

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?

canon
  • 40,609
  • 10
  • 73
  • 97
jlocker
  • 1,478
  • 1
  • 12
  • 23
  • @canon sorry i have missed it and have updated my question – jlocker Oct 03 '15 at 16:34
  • 2
    see for yourself: https://jsperf.com/caching-array-length/4 – xZ6a33YaYEfmv Oct 03 '15 at 16:35
  • @canon, that is not _my_ test. what do you mean by "numbers keep getting bigger and bigger"? also there are 53 revisions of this test and performance is almost the same. – xZ6a33YaYEfmv Oct 03 '15 at 16:42
  • The first time I measured this, some years ago, caching the length was faster. More recently I measured it again, and not catching it was slightly faster on Firefox and slightly slower on Chrome. So now I don't care anymore and I just use the short version. – Oriol Oct 03 '15 at 16:43
  • 1
    Possible duplicate of [Is reading the \`length\` property of an array really that expensive an operation in JavaScript?](http://stackoverflow.com/questions/5752906/is-reading-the-length-property-of-an-array-really-that-expensive-an-operation) – Djizeus Oct 03 '15 at 16:58

2 Answers2

2

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
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
0

each time you are calculating data.length in

for (var i = 0, c = data.length; i < c; i++)  {}
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84