2

There are two alternatives I have for executing a piece of code. The code basically resets all the values in three arrays. Two of them are int arrays and one is boolean.

Choice 1

for (i = 0; i < array1.length; i++)
    array1[i] = 0;

for (i = 0; i < array2.length; i++)
    array2[i] = 0;

for (i = 0; i < array3.length; i++)
    array3[i] = false;

Choice 2

int limit = <assign the greatest of the array lengths>

for (i = 0; i < limit; i++)
{
    if (i < array1.length)
        array1[i] = 0;

    if (i < array2.length)
        array2[i] = 0;

    if (i < array3.length)
        array3[i] = false;
}

Which of these would be faster? Given that the arrays can have varying lengths and have no relationship with each other.

There is a real good discussion here. The answer listed first explains quiet well what arrays actually mean in javascript. For those interested to check it out!

Community
  • 1
  • 1
TheSilverBullet
  • 605
  • 7
  • 21

2 Answers2

6

This version is almost certainly going to be faster. It is also easier to read and shorter, which are both much more important attributes than speed (99+% of the time).

for (i = 0; i < array1.length; i++)
    array1[i] = 0;

for (i = 0; i < array2.length; i++)
    array2[i] = 0;

for (i = 0; i < array3.length; i++)
    array3[i] = false;

In general, it is faster to access data that is close in memory to data that you accessed recently.

This version also does not suffer from additional branching you would get in the second version.

A sufficiently advanced compiler would transform the second version into the first.

Benchmarking: Micro-benchmarks are 100% useless without profiling your entire program first. Since I don't think the performance measurements are useful, I am not providing them.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • My 2c is that *shorter* is simply a contributing factor to *easier to read/understand*. If a longer alternative is, all things considered, easier to understand/clearer in its intent, then that is probably the one to go with. – Andrzej Doyle Aug 23 '12 at 10:28
  • 1
    My point was that any code which is simultaneously shorter and easier to understand is obviously good, whereas there is room for debate between long/simple code and short/opaque code. – Dietrich Epp Aug 23 '12 at 10:34
1
function reset_array(array, value) {
  var len = array.length;
  array.length = 0;
  while (len--) array.push(value);
}

reset_array(array1, 0);
reset_array(array2, 0);
reset_array(array3, false);
xdazz
  • 158,678
  • 38
  • 247
  • 274