Shuffle Arrays (v4)

Revision 4 of this benchmark created 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

Revisions

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