Native and non-native Random Numbers

JavaScript performance comparison

Revision 2 of this test case created by Adam Hyland

Info

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

Preparation code

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

var seed = [
  123456789,
  362436069,
  521288629,
  88675123
];

var denom = Math.pow(2, 32);

var xorshiftbare = function() {
  // required inputs
  var x = seed[0],
      w = seed[3];
  // derived values
  var t = x^(x << 11),
      r = w^(w >> 19)^(t^(t >> 8));
  // update the seed array
  seed = [seed[1], seed[2], w, r];
  return r / denom;
};

var xor = {
  x : 123456789,
  y : 362436069,
  z : 521288629,
  w : 88675123,
  tuple : {
    a : 11,
    b : 19,
    c : 8
  },
  denom : Math.pow(2, 32),
  shift : function() {
    //tuples
    var a = this.tuple.a,
        b = this.tuple.b,
        c = this.tuple.c;

    // inputs from the seed
    var x = this.x,
        w = this.w;
    // outputs generated from bit shifts
    var t = x^(x << a);
    // Make the ring a bit more explicit.
    this.x = this.y;
    this.y = this.z;
    this.z = this.w;
    // Chained XOR operations bring the noise
    this.w = w^(w >> b)^(t^(t >> c));

    return this.w / this.denom;
  }
};

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

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…
Bare XOR-shift
xorshiftbare();
pending…
prettier/modular XOR shift
xor.shift();
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