开发者

Why is there such a huge performance difference between complex loops and many loops

I'm working on some fast looping for a project, and I decided to throw together a simple test to see how the performance varied when comparing runnning a more complex inner loop, vs. running several simple inner loops. Here is the jsperf for it:

http://jsperf.com/nested-fo开发者_运维知识库rs-vs-iterative-fors

I'm surprised at how significant the difference appears to be.

Can anyone either point out why my test is bad (which may well be the case), or explain why the performance difference.

Thanks!

idb


I don't know why you need underscore.js and jQuery for this. I've written a non-library version that compares:

  1. 100 loops of 10 loops of 1 call each (1,000 calls)
  2. 100 loops of 10 calls (1,000 calls)
  3. 200 loops of 5 calls (1.000 calls)
  4. 1,000 loops of 1 call (1,000 calls)

The performance of each is pretty similar.

I think your issue is that the first case is 100 anonymous functions making 10 calls each. The second is 1,000 anonymous functions making one call each. The overhead is likely in creating the anonymous functions (though I have not looked at the related internal parts of the libraries being used).


In the first case you call one iterator function 100 times. In the second case, you call 10 iterator functions 100 times. That's 10 times the number of function calls. I'd say that overhead is what's causing the difference.


I think there is an apples-to-oranges issue with your tests - in your first one you loop over the array of integers 1 * 100 times for a total of 100 executions of your function (which executes your doSomething function 10 times for a total of 1,000 executions.)

Your second case loops over the array of integers 10 * 100 times for a total of 1,000 executions of 10 anonymous functions each of which calls your doSomething function once. Traversing a 100-item array 10 times will take more time than traversing it once. Creating 10 anonymous functions and calling them 100 times each is definitely more overhead than creating one anonymous function and calling it 100 times. Those two things combined make your tests completely different.

Try this instead:

function doSomething(a) {
  a * 10 + a * 1000000.0 / 50.0;
}
var range = _.range(100),
    total_runs = _.range(10);
_.each(total_runs, function(a) {
    _.each(range, doSomething);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜