Scotch Range Sum

JavaScript performance comparison

Test case created by worldclassdev

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  // USING A FOR LOOP
  function rangeSumForLoop(arr) {
    let sum = 0;
    for (i = arr[0]; i <= arr[1]; i++) {
      sum += i;
    }
    return sum;
  }
  
  // USING THE ARITHMETIC PROGRESSION FORMULA
  function rangeSumAP(arr) {
    let arrList = [];
    for (i = arr[0]; i <= arr[1]; i++) {
      arrList.push(i);
    }
    return (arrList.length * (arr[0] + arr[1])) / 2;
  }
  
  // USING RECURSION
  function rangeSumRecursion(arr) {
    if (arr[0] == arr[1]) {
      return arr[0];
    } else {
      return rangeSumRecursion([arr[0], arr[1] - 1]) + arr[1];
    }
  }
  
  // USING .REDUCE()
  function rangeSumReduce(arr) {
    let arrList = [];
    for (i = arr[0]; i <= arr[1]; i++) {
      arrList.push(i);
    }
    return arrList.reduce((acc, num) => acc + num, 0);
  }
  

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Forloop
rangeSumForLoop([1,50])
pending…
AP Formula
rangeSumAP([1,50])
pending…
Recursion
rangeSumRecursion([1,50])
pending…
Using .reduce()
rangeSumReduce([1,50])
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.

0 Comments