many loops or many function calls

JavaScript performance comparison

Test case created

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.

Testing in unknown unknown
Test Ops/sec
one loop, many functions
for (i = 0; i < len; i++) {
process1(numbers[i]);
process2(numbers[i]);
process3(numbers[i]);
}
pending…
few functions, many loops
process1loop(numbers);
process2loop(numbers);
process3loop(numbers);
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:

1 comment

alec commented :

Looks like it depends on the processes. The more expensive the processes, the more expensive looping many times becomes.

Add a comment