Reputation: 4218
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-fors-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
Upvotes: 3
Views: 257
Reputation: 147403
I don't know why you need underscore.js and jQuery for this. I've written a non-library version that compares:
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).
Upvotes: 3
Reputation: 159905
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);
});
Upvotes: 1
Reputation: 522081
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.
Upvotes: 1