Last active
October 5, 2023 20:35
-
-
Save Juraj-Masiar/c85f708f187c2e7db911da08e0e8c20a to your computer and use it in GitHub Desktop.
How many times do you need to call `Math.random()` to get a collision? (Firefox will tell you, Chrome may not!)
This file contains 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
// This is a simple experiment to see how likely it is to get a collision when using Math.random() | |
(() => { | |
const numbersSet = new Set(); | |
while (true) { | |
const random = Math.random(); | |
// const random = crypto.randomUUID(); | |
if (numbersSet.has(random)) { | |
console.log(`Set size: ${numbersSet.size.toLocaleString()}, collision: ${random}`); | |
break; | |
} | |
else numbersSet.add(random); | |
} | |
})(); | |
// Conclusions: | |
// - Chrome "Set" can handle only a few millions of items :( | |
// - Set will consume gigabytes of RAM in short time! | |
// - collision will appear after generating roughly between 10 - 200 millions of random numbers | |
// - for more collision free random you can use "crypto.randomUUID" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment