Search code examples
javascriptperformancenested-loops

Two loops performance difference. Swapping inner and outer loop


I had two loops (one nested in the other one) and I was wondering if there is any difference in how I nest these loops. Results of Code 1 and Code 2 are the same (100,000x4 = 4x100,000 = 400,000) but jsPerf shows that Code 2 is roughly 50% faster than Code 1.

I'd like to kindly ask for your advice, I don't understand the difference between the two.

Thank you very much.

var tt = function () {
      // do some stuff
      // for example:
      return (3);
    };

Test code 1:

for (var i = 0; i < 100000; i++) {
  for (var j = 0; j < 4; j++) {
    tt();
  }
}

Test code 2:

for (var j = 0; j < 4; j++) {
  for (var i = 0; i < 100000; i++) {
    tt();
  }
}

Solution

  • The difference is in the loop initialization code. The first code has to initialize the inner loop 100,000 times while the second one only does that 4 times.