underscore shuffle vs my shuffle

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

<script src="http://underscorejs.org/underscore-min.js"></script>

<script>
function shuffle(obj, rounds, deep) {
    var length = obj.length,
        i,
        j,
        rnd,
        tmp;

    if (length < 2) {
        return;
    }

    rounds = rounds >>> 0 || 1;
    deep = deep === true;

    j = 0;
    while (j < rounds) {
        i = 0;
        while (i < length) {
            if (Array.isArray(obj[i])) {
                shuffle(obj[i], rounds, deep);
            }

            rnd = Math.floor(Math.random() * i);
            tmp = obj[i];
            obj[i] = obj[rnd];
            obj[rnd] = tmp;
            i += 1;
        }

        j += 1;
    }
}
</script>
<script>
Benchmark.prototype.setup = function() {
    var i,
      array = [],
      rolls = 300;
   
    for (i = 0; i < 30000; i += 1) {
      array.push(i);
    }
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
underscore
_.shuffle(array);
array.slice(0, rolls);
pending…
my shuffle
shuffle(array);
array.slice(0, rolls);
pending…
alternative to shuffle
var store = {},
  result = [],
  undef,
  length = array.length;

if (rolls > length) {
  rolls = length;
}

i = 0;
while (i < rolls) {
  var rnd = Math.floor(Math.random() * length);

  if (store[rnd] === undef) {
    result[i] = store[rnd] = array[rnd];
    i += 1;
  }
}
pending…
underscore old
var shuffled = [],
  rand;
_.each(array, function(value, index, list) {
  if (index == 0) {
    shuffled[0] = value;
  } else {
    rand = Math.floor(Math.random() * (index + 1));
    shuffled[index] = shuffled[rand];
    shuffled[rand] = value;
  }
});
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. Here’s a list of current revisions for this page:

0 comments

Add a comment