Created
November 12, 2022 04:25
-
-
Save DarrenSem/f664b66ef78b4efbb103a88afea625da to your computer and use it in GitHub Desktop.
shuffle.js - fastest possible after countless speed comparisons - minified to 76 characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?