0

How big is the performance difference between

for (var i = 0, max = array.length; i < max; i++)

and

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

How do the different browsers handle the length of an array? Does the length function of an array always count all objects insinde the array or is there a variable inside the array object (or in the browser) which stored the current length of the array? Does some browsers optimize the code?

Christoph
  • 1,993
  • 1
  • 25
  • 33
  • I think the way is to profile it and see the difference – Arun P Johny Feb 10 '16 at 07:53
  • https://jsperf.com/array-length-vs-cached - should answer your question – Arun P Johny Feb 10 '16 at 07:53
  • @ujwaldhakal, You got to be kidding :P – Rayon Feb 10 '16 at 07:55
  • I benchmarked it, the first method is faster. But i want to know more about the background. – Christoph Feb 10 '16 at 07:56
  • @Cristoph The background mostly depends on the specific implementation, but under the hood you are likely dereferencing an object that lives on the heap or accessing a hash map when you read a property in JavaScript, so you incur in a bunch of instructions and cache misses that hit the performance. That's just to give you an idea of what it could be due to, I don't want (and I am not enough skilled) to give more detailed information. – skypjack Feb 10 '16 at 08:05

0 Answers0