1

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();
  }
}
Vico Lemp
  • 133
  • 12
  • possible duplicate of http://stackoverflow.com/q/11227809/1903116 – thefourtheye Dec 28 '14 at 13:08
  • Er, it appears to me that the only thing this question has to do with the proposed dupe is the presence of the "performance" tag :-) It's a totally different language, this one involves no sorting, and so on. – paxdiablo Dec 28 '14 at 13:13
  • @paxdiablo I would assume that the processor bets that the inner loop will not be terminated soon in the first case, but it fails every time. So, it has to realign and it costs too much. – thefourtheye Dec 28 '14 at 13:15

2 Answers2

2

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.

unobf
  • 7,158
  • 1
  • 23
  • 36
1

Analyze the code as if each operation had a cost and you will see that this makes sense.

In test code 2, you are stuck on the nested loop 100,000 times, but go to the outer loop 4 times. Instead, in test code 1, you alternate between the two.

The first test code runs more operations than the seconds.

Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • I see thank you very much. I don't know which answer set with the green tick because they are both same. So I mark the other one because it seems a slightly simplier explanation. I hope you don't mind. PS: Tip each operation has a cost, I will remember that, when it comes to natural functionality I tend to forget there is something behind it too xD, so it's a precious advice for a beginner like me, thank you. – Vico Lemp Dec 28 '14 at 13:45