问题
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