Native and non-native Random Numbers

JavaScript performance comparison

Revision 3 of this test case created by Adam Hyland and last updated

Info

Comparison of performance for native Math.random(), a seedable random number generator written by David Bau, a seedable LCG and a seedable XOR shift generator.

Part of the relative performance differences across browsers is explained by the different RNGs implemented in each engine. Chrome uses an MWC variant, FF uses a simpler linear shift generator and Webkit2 uses a newer block cipher.

Preparation code

<script src="http://davidbau.com/encode/seedrandom-min.js"></script>
<script type="text/javascript">

var xor = (function() {
  var denom = Math.pow(2, 31),
      tuple = { a : 11, b : 19, c : 8},
      seed = 2463534242;
  return {
    getSeed : function() {
      return seed;
    },
    setSeed : function(val) {
      seed = val || Math.random() * denom;
      return seed;
    },
    rand : function() {
      //tuples
      var a = tuple.a,
          b = tuple.b,
          c = tuple.c;

      var x = seed,
          t, y;

      t = x^(x << a);
      seed = y = (x^(x >> c))^(t^(t >> b));

      return y / denom;
    }
  };
}());

var lcg = (function() {
  // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
  var m = 4294967296,
      a = 1664525,
      c = 1013904223,
      seed, z;
  return {
    setSeed : function(val) {
      z = seed = val || Math.random() * m;
    },
    getSeed : function() {
      return seed;
    },
    rand : function() {
      z = (a * z + c) % m;
      return z / m;
    }
  };
}());

</script>
<script>
Benchmark.prototype.setup = function() {
    Math.oldrand = Math.random;
    Math.seedrandom();
    lcg.setSeed();
};

Benchmark.prototype.teardown = function() {
    Math.random = Math.oldrand;
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Native Math.random
Math.oldrand();
pending…
Bau's ARC4
Math.random();
pending…
XORshift
xor.rand();
pending…
LCG
lcg.rand();
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. Here’s a list of current revisions for this page:

0 comments

Add a comment