js生成java uuid,javascript生成的uuid的独特性和随机性如何?

I'm considering generating unique identifiers for data in javascript using one of the uuid methods discussed here. Most likely something along the lines of this one since it uses window.crypto if it's available.

These id's don't need to be globally unique, only unique per user. Will this generate sufficiently unique ids for a large scale application? Is there any reason to think this will result in id collisions? Can javascript generate a sufficiently random uuid for this to work? It looks like window.crypto is fairly widely available and this particular project already requires reasonably modern browsers.

MORE INFO: some background about the problem can be found here

解决方案

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:

function getUUID() {

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值