Recursion vs For Loop vs While Loop (v7)

Revision 7 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(i);
}
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(arr, func, vars){
            var i = -1;
        },
        theprocess: function(arr, i, vars, func){

            //arr[i+1] ? func(arr,i++, vars) : callback(vars) ;
            if(arr[i+1]){
                i++;
                if(func(arr,i, vars) === true){
                    return vars;
                }
                //i++;
            }else{
                return vars;
            }
            //console.log(arr[i]);
        },
        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+'}');
    delete thestring;
    return thefunc;
}
evalmethod = evalmethodset(10001);

  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;
  }
</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,thefunc,{total:0});
ready

Revisions

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