Skip to content

Instantly share code, notes, and snippets.

@DarrenSem
Created November 12, 2022 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarrenSem/f664b66ef78b4efbb103a88afea625da to your computer and use it in GitHub Desktop.
Save DarrenSem/f664b66ef78b4efbb103a88afea625da to your computer and use it in GitHub Desktop.
shuffle.js - fastest possible after countless speed comparisons - minified to 76 characters
// shuffle.js
// minified = 76 chars (not including 'R=Math.random') s=a=>{for(let b,c,d=a.length-1;0<d;)b=0|R()*(d+1),c=a[d],a[d--]=a[b],a[b]=c}
// after doing console.time speed comparisons of Every. Possible. Version and logic permutation I could find:
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
// https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
// https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
// pre-cached "R" faster because no OBJECT.KEY lookup each time
let R = Math.random;
let shuffleFastestPossible = array => {
// let seemed slightly faster than var (or does it compile to same?)
let i = array.length - 1, x, temp;
// while slightly faster than for() probably due to less overhead when you include (all;three;parts)
while(i > 0) {
// "calc | 0" faster than "Math.floor(calc)": bitwise math, no OBJECT.KEY lookup
x = R() * (i + 1) | 0;
// temp faster than destructuring [array[x], array[i--]] = [array[i], array[x]]
temp = array[i];
array[i--] = array[x];
array[x] = temp;
};
};
@DarrenSem
Copy link
Author

22 REVISIONS (as of 18Dec2023) -- but apparently was last edited Apr 27, 2020 so I am curious if there really is a performance hit using "their" version compared to above (when running thousands of times, e.g. Catan map generator) so... perhaps time to benchmark this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment