Skip to content

Instantly share code, notes, and snippets.

@Juraj-Masiar
Last active October 5, 2023 20:35
Show Gist options
  • Save Juraj-Masiar/c85f708f187c2e7db911da08e0e8c20a to your computer and use it in GitHub Desktop.
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 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