JavaScript Array.shuffle (v4)

Revision 4 of this benchmark created on


Description

Comparing various implementations of Array.shuffle in JavaScript, made for 140byt.es.

Setup

var a = [],
      b;
    for (var i = 0; i < 1000; i++)
      a.push((Math.random() * 1000) | 0);
    var s1 = function(a, b, c) {
      for (b = a.length; b; c = 0 | b * Math.random(), a[c] = [a[--b], a[b] = a[c]][0]);
    }
    var s2 = function(a) {
      a.sort(function() {
        return .5 - Math.random()
      })
    }
    var s3 = function f(a) {
      return a.pop ? a.sort(f) : .5 - Math.random()
    }
    var s4 = function(d, a, b, c) {
      a = d.length, b, c, d;
      while (--a) {
        b = Math.floor(Math.random() * (a - 1));
        c = d[a];
        d[a] = d[b];
        d[b] = c;
      }
    };
    
    
    var s5 = function(a) {
      var b, c, d;
      for (b = a.length; --b > 0;) c = ~~ (Math.random() * (b + 1)), d = a[c], a[c] = a[b], a[b] = d;
      return a
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Fisher-Yates shuffle
s1(a.slice(0));
ready
Sort shuffle
s2(a.slice(0));
ready
Fisher-Yates shuffle 3
s5(a.slice(0));
ready
Fisher-Yates shuffle2
s4(a.slice(0));
ready

Revisions

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