Shuffle Arrays

Benchmark created by EtnasSoft on


Description

Testing methods for shuffle Javascript arrays

Setup

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];

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;
}

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;
}

shuffle( myArray );
 
ready

Revisions

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