javascriptarraysfor-loop

In a nested for loop, is there any advantage in starting with the longer loop? Or vice versa?


For example:

var longArray = [1, 2, 3, 4]
var shortArray = [2, 3]

Which one is faster?

Long loop first:

for (var i = 0; i < longArray.length; i++) {
  for (var j = 0; j < shortArray.length; j++) {
    if (longArray[i] === shortArray[j]) {
      // do something
    }
  }
}

Or short loop first:

for (var i = 0; i < shortArray.length; i++) {
  for (var j = 0; j < longArray.length; j++) {
    if (longArray[i] === shortArray[j]) {
      // do something
    }
  }
}

Or are there any advantages in either that I'm not considering? Or does it not matter at all?


Solution

  • Short loop first is generally faster, only because it spends more time visiting elements in the same order as they tend to be laid out in memory. You need longArray to have a lot more elements, at least several thousand. Here is a test case to demonstrate the difference: https://jsperf.com/loop-order-sl

    For the arrays you posted, which has a longArray that is relatively small, there is negligible difference in performance. The shorter array might be a tiny bit faster as @Ajaypayne observed or vice-versa depending on environment.