How Unique And Random Are Javascript Generated Uuids?
Solution 1:
From the comments on this answer:
... (cont'd) The odds of two IDs generated by this function colliding are, literally, astronomically small. All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide. – broofa
That's a 1 in 5,316,911,983,139,663,491,615,228,241,121,378,304 (5.3 undecillion) chance of collision.
Also make sure to validate that when a user attempts to create a new record with this uuid, that the uuid is not already in use. This falls under the larger strategy of never trusting user input.
You can also test this generator if you aren't convinced:
functiongetUUID() {
return'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
var uuids = [];
var last;
var numGenerated = 0;
do {
last = getUUID();
if (uuids.indexOf(last) === -1) {
uuids.push(last);
numGenerated++;
console.log(numGenerated);
} else {
break;
}
} while (true);
console.log('Got collision after ' + numGenerated + ' generated UUIDS.');
I'm running it in Node.js (V8) right now and am still collision-free after 170,000 ids. Edit: 240,000.
Post a Comment for "How Unique And Random Are Javascript Generated Uuids?"