Two loops performance difference. Swapping inner and outer loop

我的未来我决定 提交于 2021-02-17 03:45:13

问题


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();
  }
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27676638/two-loops-performance-difference-swapping-inner-and-outer-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!