underscore shuffle

Benchmark created by evilive on


Preparation HTML

<script src='http://underscorejs.org/underscore-min.js'></script>
<script src='http://code.jquery.com/jquery.js'></script>

<script>
var _shuffle = function(arr){
  return _.shuffle(arr);
}

var sortbyrandom = function(arr){
  arr = arr.slice();
  return arr.sort(function() { return 0.5 - Math.random(); });
}

function knut3(arr) {
  arr = arr.slice();

  var m = arr.length, t, i;
  while (m) {
    i = Math.floor(Math.random() * m--);
    t = arr[m];
    arr[m] = arr[i];
    arr[i] = t;
  }
  return arr;
}

</script>

<style>
.debug-block {
  border: 1px solid black;
  margin-bottom: 15px;
}
.debug-block span:first-child {
  font-weight: bold;
  display: block;
}
.failed {background: salmon;}
.passed {background: lightblue;}
</style>

<i>Example output from methods. (lightblue - passed; salmon - failed)</i>
<div id="debug"></div>
<script>
var $debug = $('#debug');
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'foo', 'bar', true, false];

function test(arr, func) {
  arr = _.clone(arr);
  var res = func(arr), testOk = true;
  if (!_.isEmpty(_.difference(arr, res))) {
    console.log('diff', _.difference(arr, res));
    testOk = false; 
  }
  if (arr.join(',') == res.join(',')) {
    console.log('not shuffled', arr.join(','), res.join(','));
    testOk = false;
  }
  if (arr.sort().join(',') != res.sort().join(',')) {
    console.log('not same', arr.sort().join(','), res.sort().join(','));
    testOk = false;
  }
  return testOk;
}

function debugWrite(testname, arr, func) {
  var $div = $('<div></div>', {class:'debug-block'});
  $div.addClass(test(arr, func) ? 'passed' : 'failed');
  var html = '<span>'+testname+'</span>';
  html += '<span>'+JSON.stringify(func(arr))+'</span>';
  $div.html(html);
  $debug.append($div);
}

/******************************************/
debugWrite('_shuffle', arr, function (o) { return _shuffle(o); });
debugWrite('sortbyrandom', arr, function (o) { return sortbyrandom(o); });
debugWrite('knut3', arr, function (o) { return knut3(o); });
/******************************************/

var arr = [];
for (var i = 0; i < 100; i++) {
  arr[i] = i;
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
_shuffle
_shuffle(arr);
ready
native sort by random
sortbyrandom(arr);
ready
Knuth-Fisher-Yates
knut3(arr);
ready

Revisions

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