Recursion vs For Loop vs While Loop

JavaScript performance comparison

Revision 4 of this test case created

Info

Fixing the while loop.

Preparation code

<script>
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
  function sum_recurse(arr, i) {
   i = i || 0;
   var len = arr.length;

   function better_recurse(arr, i) {
      if (i > len) {
         return 0;
      } else {
         return arr[i] + better_recurse(arr, i + 1);
      }
   }
  }
  function sum_while(arr) {
   var total = 0,
       i = arr.length;
 
   while (i--) {
    total += arr[i];
   }
 
   return total;
  }
 
  function sum_for(arr) {
   var total = 0,
       len = arr.length;
 
   for (var i = 0; i < len; i++) {
    total += arr[i];
   }
 
   return total;
  }
</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
Recurse
sum_recurse(nums);
pending…
While Loop
sum_while(nums);
pending…
For Loop
sum_for(nums);
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:

0 comments

Add a comment