Standard Deviation

JavaScript performance comparison

Test case created by RobG

Info

Test speed of standard deviation implementations

Preparation code

<script>
  Math.stDev = function (a) {
      var n = a.length;
      var v = a.reduce(function (v, x) {
        v[0] += x * x;
        v[1] += x;
        return v;
      }, [0,0]);
      return Math.sqrt( (v[0] - v[1]*v[1]/n) / (n - 1) );
  }
 
 
  Math.mean= function(array){
      return array.reduce(function(a, b){ return a+b; })/array.length;
  }
 
  Math.stDeviation=function(array){
      var mean= Math.mean(array);
      dev= array.map(function(itm){return (itm-mean)*(itm-mean); });
      return Math.sqrt(dev.reduce(function(a, b){ return a+b; })/array.length);
  }
 
  function stDev(a) {
    var n = a.length;
    var i = n, m, v, x = 0, y = 0;
    while (i) {
      v = a[--i];
      x += v*v;  // sum squares
      y += v;    // sum terms
    }
    return Math.sqrt( (x - y*y/n) / n );
  }
 
  Math.stDev2 = function (a) {
      var n = a.length;
      var v = [0,0];
      a.reduce(function (t, x) {
        v[0] += x * x;
        v[1] += x;
      }, v);
      return Math.sqrt( (v[0] - v[1]*v[1]/n) / n );
  }
 
 
 
  var arr = [2,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9,4,4,4,5,5,7,9,2,4,4,4,5,5,7,9];
</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
Multiple reduce call
Math.stDeviation(arr);
pending…
Single reduce call
Math.stDev(arr);
pending…
Simple function
stDev(arr);
pending…
Single reduce call faster?
Math.stDev2(arr);
pending…

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

Compare results of other browsers

0 comments

Add a comment