Recursion vs For Loop vs While Loop (v10)

Revision 10 of this benchmark created by Kyle on


Description

Stop using array.slice for high-performance code!

Preparation HTML

<script>
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  
  function sum_recurse(arr, i) {
   var i = i || 0;
   if (i === arr.length) { return 0; }
    return arr[i] + sum_recurse(arr, i + 1);
  }
  
  function sum_while(arr) {
   var total = 0,
       i = 0,
       len = arr.length;
  
   while (i < len) {
    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

Ready to run.

Testing in
TestOps/sec
Recurse
sum_recurse(nums);
ready
While Loop
sum_while(nums);
ready
For Loop
sum_for(nums);
ready
Reduce
nums.reduce(function(x, y) {
  return x + y
});
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.