fyshuffle

JavaScript performance comparison

Revision 6 of this test case created by

Preparation code

<script>
function numberArray(a,b){
 b=[];while(a--)b[a]=a+1;return b
}
var array100=numberArray(100),
    array1000=numberArray(1000);

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

Array.prototype.shuffle = function() {
  var i = this.length, j, temp;
  if ( i == 0 ) return this;
  while ( --i ) {
     j = Math.floor( Math.random() * ( i + 1 ) );
     temp = this[i];
     this[i] = this[j];
     this[j] = temp;
  }
  return this;
}

function fy(a,b,c,d){
 c=a.length;while(c)b=Math.random()*(--c+1)|0,d=a[c],a[c]=a[b],a[b]=d
}

Array.prototype.randomize = function () {
    this.sort(function () {
        return Math.random() < 0.5 ? -1 : 1;
    });
    return this;
};

</script>
    

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
shuffle
shuffle(array100);
shuffle(array1000)
pending…
shuffleArray
shuffleArray(array100);
shuffleArray(array1000)
pending…
shuffle prototype
array100.shuffle();
array1000.shuffle()
pending…
fy
fy(array100);
fy(array1000)
pending…
randomize prototype
array100.randomize();
array1000.randomize()
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.

0 Comments