many loops or many function calls
JavaScript performance comparison
Info
In a case where you are repeatedly performing a few operations/functions on many array items, is it faster to loop through the array items once and call each function on each index, or to loop through the array items as many times as there are operations, but only calling each function once.
Preparation code
<script>
Benchmark.prototype.setup = function() {
var numbers = [];
var len = 200;
for (var i = 0; i < len; i++) {
numbers[i] = i * 10; }
function process1 (x) {
x = Math.sqrt(x);
x = Math.sqrt(x);
x = Math.sqrt(x); };
function process2 (x) {
x = Math.cos(x);
x = Math.cos(x);
x = Math.cos(x); };
function process3 (x) {
x = Math.log(x);
x = Math.log(x);
x = Math.log(x); };
function process1loop (a) {
for (i = 0; i < len; i++) {
a[i] = Math.sqrt(a[i]);
a[i] = Math.sqrt(a[i]);
a[i] = Math.sqrt(a[i]);
}
}
function process2loop (a) {
for (i = 0; i < len; i++) {
a[i] = Math.cos(a[i]);
a[i] = Math.cos(a[i]);
a[i] = Math.cos(a[i]);
}
}
function process3loop (a) {
for (i = 0; i < len; i++) {
a[i] = Math.log(a[i]);
a[i] = Math.log(a[i]);
a[i] = Math.log(a[i]);
}
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
Test  Ops/sec  

one loop, many functions 

pending… 
few functions, many loops 

pending… 
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit
to the URL. Here’s a list of current revisions for this page:
 Revision 1: published
 Revision 2: published by alec
 Revision 3: published
1 comment
alec commented : ∞
Looks like it depends on the processes. The more expensive the processes, the more expensive looping many times becomes.