Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

random - Collisions when generating UUIDs in JavaScript

This relates to this question. I am using the code below from this answer to generate a UUID in JavaScript:

'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);
});

This solution appeared to be working fine, but I am getting collisions. Here's what I have:

  • A web application running in Google Chrome.
  • 16 users.
  • about 4000 UUIDs have been generated in the past two months by these users.
  • I got about 20 collisions - e.g., a new UUID generated today was the same as about two months ago (different user).

What is causing this issue and how can I avoid it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Indeed there are collisions, but only under Google Chrome. Check out my experience on the topic in Google Chrome random number generator issue

It seems like collisions only happen on the first few calls of Math.random. Because if you just run the createGUID / testGUIDs method above (which obviously was the first thing I tried), it just works without any collisions whatsoever.

So to make a full test one needs to restart Google Chrome, generate 32 byte, restart Chrome, generate, restart, generate, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...