Math.random vs Xorshift

JavaScript performance comparison

Test case created by spleen

Info

Math.random() vs Xorshift.random()

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function Xorshift() {
      var self = this,
         seeds = (arguments.length) ? Array.prototype.slice.call(arguments) : [new Date().getTime()],
         x = 123456789,
          y = 362436069,
          z = 521288629,
          w = 88675123,
          v = 886756453;
   
      self.uint32 = function() {
        var t = (x ^ (x >>> 7)) >>> 0;
        x = y;
        y = z;
        z = w;
        w = v;
        v = (v ^ (v << 6)) ^ (t ^ (t << 13)) >>> 0;
        return ((y + y + 1) * v) >>> 0;
      };
   
      self.fract53 = function() {
        return self.random() + (self.uint32() & 0x1fffff) * 1.1102230246251565e-16;
      };
   
      for (var i = 0, len = seeds.length, seed; i < len; i++) {
        seed = seeds[i];
        x ^= mash(seed) * 0x100000000;
        y ^= mash(seed) * 0x100000000;
        z ^= mash(seed) * 0x100000000;
        v ^= mash(seed) * 0x100000000;
        w ^= mash(seed) * 0x100000000;
      }
   
      self.random = function() {
        return self.uint32() * 2.3283064365386963e-10;
      }
   
    self.mash = function(data) {
      data = data.toString();
      var n = 0xefc8249d,
          i = 0,
          len = data.length;
   
      for (i = 0; i < len; i++) {
        n += data.charCodeAt(i);
        var h = 0.02519603282416938 * n;
        n = h >>> 0;
        h -= n;
        h *= n;
        n = h >>> 0;
        h -= n;
        n += h * 0x100000000;
      }
   
      return (n >>> 0) * 2.3283064365386963e-10;
   
    }
   
    }
   
   
   
};
</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
Math.random()
a = Math.random();
pending…
Xorshift.random()
xor = new Xorshift();
a = xor.random();
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