0

I know that JavaScript is an interpreted language, which doesn't have the benefits of code optimization that may be done for a compiled language.

So I was curious, which would be better to use?

A. With .length in the loop:

//Assuming 'arr' in an array of an arbitrary length
for(var i = 0; i < arr.length; i++)
{
    //Do work on element arr[i];
}

B. or this:

//Assuming 'arr' in an array of an arbitrary length
var arrLen = arr.length;
for(var i = 0; i < arrLen; i++)
{
    //Do work on element arr[i];
}
c00000fd
  • 20,994
  • 29
  • 177
  • 400
  • 1
    It depends on the JS interpreter and how often the code is run. In general, caching the length speeds things up, but if the code is run a lot, many implementations have a just-in-time compiler that will compile it so it is effectively cached by the interpreter instead of your code. – Mark Reed Aug 26 '14 at 20:24
  • Try it and tell us the answer: http://stackoverflow.com/questions/313893/how-to-measure-time-taken-by-a-function-to-execute – Kai Mattern Aug 26 '14 at 20:24
  • Not much difference: http://jsperf.com/fastest-array-loops-in-javascript/56 – Diodeus - James MacFarlane Aug 26 '14 at 20:25
  • See http://stackoverflow.com/questions/25460123/what-are-the-pros-and-cons-to-assigning-the-end-point-of-a-for-loop/25460215#25460215 – Barmar Aug 26 '14 at 20:25

0 Answers0