Fisher-Yates shuffle

JavaScript performance comparison

Revision 3 of this test case created

Info

Compare two variations of a Fisher-Yates shuffle

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var orderedlist = ["000","001","002","003","004","005","006","007","008","009","010","011","012","013","014","015","016","017","018","019","020","021","022","023","024","025","026","027","028","029","030","031","032","033","034","035","036","037","038","039","040","041","042","043","044","045","046","047","048","049","050","051","052","053","054","055","056","057","058","059","060","061","062","063","064","065","066","067","068","069","070","071","072","073","074","075","076","077","078","079","080","081","082","083","084","085","086","087","088","089","090","091","092","093","094","095","096","097","098","099"];
   
   
    // Fisher-Yates shuffles
    function shuffle1(array) {
      var i = array.length, j, t;
      while (--i > 0) {
        j = ~~(Math.random() * (i + 1));
        t = array[j];
        array[j] = array[i];
        array[i] = t;
      }
      return array;
    }
   
   
    function shuffle2(array) {
      var tmp, current, top = array.length;
      if(top) while(--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
      }
      return array;
    }
   
    function shuffle3(array) {
      var tmp, current, top = array.length;
      if(top) while(top) {
        current = Math.floor(Math.random() * (top--));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
      }
      return array;
    }
   
};
</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
Fisher-Yates Shuffle1
shuffle1(orderedlist);
pending…
Fisher-Yates Shuffle2
shuffle2(orderedlist);
pending…
Fisher-Yates Shuffle3
shuffle3(orderedlist);
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