Recursion vs For Loop vs While Loop (v8)

Revision 8 of this benchmark created on


Description

Write code on the fly

Preparation HTML

<script>
  var nums = [];
for (var i = 0; i <= 500; i++) {
    nums.push(~~(Math.random()*10000));
}
function thefunc(arr, i, vars){

    vars.total += arr[i];
    //console.log(vars.total, arr, i);
}
function evalmethodset(maxsize) {
    var ti = maxsize;
    var x = {
        thestart: function(thearr){
            var total = 0;
            var i = -1;
        },
        theprocess: function(thearr, total, i){
            i++;
            if(thearr[i]){
                total += thearr[i];
            }else{
                return total;
            }
        },
        thefinish: function(total){
            return total;
        }
    };
    function newFilledArray(length, val) {
        for (var array = [],i = 0; i < length; i++) {
            array[i] = val;
        }
        return array;
    }
    var thereg = /(function\s?)([^\.])([\w|,|\s|-|_|\$]*)(.+?\{)([^\.][\s|\S]*(?=\}))/;
    var thestring = '';
    var theprocessstart = x.thestart.toString().match(thereg);
    var theprocesscode = x.theprocess.toString().match(thereg);
    var theprocessfinish = x.thefinish.toString().match(thereg);
    thestring += theprocessstart[5];
    var i = 0;
    for(i;i<=ti;i++){
        thestring += theprocesscode[5];
    }
    i = 0;
    thestring += theprocessfinish[5];
    var thefunc;
    eval('thefunc = function('+theprocessstart[3]+'){'+thestring+'}');
    return thefunc;
}
evalmethod = evalmethodset(1000);

  function sum_recurse_set(arr) {
    var ti = arr.length - 1, i = 0, total = 0, thearr = arr, rtn;
    function go(total, thearr, i,go){
        total += thearr[i];
        if(i !== ti){
            i++;
             return go(total, thearr, i,go);
        }else{
            return total;
        }
    }
function foo(){
   return go(total, thearr, i,go);
}
    return foo;
}
  sum_recurse = sum_recurse_set(nums);
  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;
  }
function popMethod(arr){
  var sum=0,x;
arr.unshift('magickey')
while (x = arr.pop()) {
  if(x != 'magickey'){
  sum += x;
arr.unshift(x);
  }else{return sum}
  
}
return sum;
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Recurse
sum_recurse();
ready
While Loop
sum_while(nums);
ready
For Loop
sum_for(nums);
ready
eval ninja method
evalmethod(nums);
ready
pop method
popMethod(nums);
ready

Revisions

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