Fisher-Yates Array Shuffle (v2)

Revision 2 of this benchmark created on


Description

Fisher-Yates Array Shuffle variants: reduce vs forEach vs for

Setup

function rand(max = 1, min = 0) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function shuffleArrayReduce(array) {
  return array.reduceRight(
    (acc, _, i) => {
      const j = rand(i);
      [acc[i], acc[j]] = [acc[j], acc[i]];
      return acc;
    },
    [...array]
  );
}

const shuffleReduceNoSpread = arr => arr.reduceRight((r,_,__,s) => 
        (r.push(s.splice(0|Math.random()*s.length,1)[0]), r),[])
        

function shuffleArrayFor(array) {
  const a = [...array];
  for (i = array.length - 1; i > 0 ;i--) {
  	const j = rand(i);
  	[a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

function shuffleArrayForEach(array) {
  const a = [...array];
  array.forEach((_, i) => {
  	const j = rand(i);
  	[a[i], a[j]] = [a[j], a[i]];
  })
  return a;
}

function shuffleArraySort(array) { 
   return array.sort( ()=>Math.random()-0.5 );
} 

const arr = [...Array(256)].map(() => rand(1024))

Test runner

Ready to run.

Testing in
TestOps/sec
reduceRight
shuffleArrayReduce(arr);
ready
for
shuffleArrayFor(arr);
ready
forEach
shuffleArrayForEach(arr);
ready
shuffleArraySort(arr)
shuffleArraySort(arr);
ready
shuffleReduceNoSpread
shuffleReduceNoSpread(arr)
ready

Revisions

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