Fisher-Yates Array Shuffle

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

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

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

Revisions

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