Shuffle Arrays (v8)

Revision 8 of this benchmark created by David Simon on


Description

Testing methods for shuffle Javascript arrays

Setup

var i, myArraySize = 1000,
        myArray = []
        
        
        
    for (var i = 0; i < myArraySize; i++) {
      myArray.push(i);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Quadratic
function shuffle(array) {
  var copy = [],
      n = array.length,
      i;

  // While there remain elements to shuffle…
  while (n) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * n--);

    // And move it to the new array.
    copy.push(array.splice(i, 1)[0]);
  }

  return copy;
}

myArray = shuffle(myArray);
ready
In-Place Shuffle
function shuffle(array) {
  var m = array.length,
      t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m);

    // And swap it with the current element.
    t = array[--m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

myArray = shuffle(myArray);
ready
http://jsfromhell.com/array/shuffle
shuffle = function(v) {
  for (var j, x, i = v.length; i; j = (Math.random() * i) << 0, x = v[--i], v[i] = v[j], v[j] = x);
  return v;
};
myArray = shuffle(myArray);
ready
sort()
function shuffle(array) {
  var shuffler = function() {
      return Math.random() > Math.random() ? 1 : -1;
      }
      
      
      
  return array.sort(shuffler);
}

myArray = shuffle(myArray);
ready
splice()
function shuffle( arr ) { 
                for ( var i = 0, shuffled = []; arr.length != 0; ) {
                                shuffled[i++] = arr[ random = ( Math.random() * arr.length ) >> 0 ];
                                arr.splice( random, 1 );
                }
                
                return shuffled;
}

myArray = shuffle( myArray );
ready

Revisions

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