Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to verify the uniqueness of a GUID?

Tags:

c#

.net

guid

I saw this function in a source written by my coworker

private String GetNewAvailableId()
{
    String newId = Guid.NewGuid().ToString();

    while (clientsById.ContainsKey(newId))
    {
        newId = Guid.NewGuid().ToString();
    }

    return newId;
}

I wonder if there is a scenario in which the guid might not be unique? The code is used in a multithread scenario and clientsById is a dictionary of GUID and an object

like image 841
Mehran Avatar asked Aug 26 '11 12:08

Mehran


2 Answers

This should be completely unneccessary - the whole point of GUIDs is to eliminate the need for these sorts of checks :-)

You may be interesting in reading this interesting post on GUID generation algorithms:

  • GUIDs are globally unique, but substrings of GUIDs aren't (The Old New Thing)

The goal of this algorithm is to use the combination of time and location ("space-time coordinates" for the relativity geeks out there) as the uniqueness key. However, timekeeping is not perfect, so there's a possibility that, for example, two GUIDs are generated in rapid succession from the same machine, so close to each other in time that the timestamp would be the same. That's where the uniquifier comes in. When time appears to have stood still (if two requests for a GUID are made in rapid succession) or gone backward (if the system clock is set to a new time earlier than what it was), the uniquifier is incremented so that GUIDs generated from the "second time it was five o'clock" don't collide with those generated "the first time it was five o'clock".

The only real way that you might ever have a collision is if someone was generating thousands of GUIDs on the same machine while also repeatedly setting the timestamp back to the same exact point in time.

like image 97
Justin Avatar answered Nov 15 '22 00:11

Justin


By definition, GUID's are unique (Globally unique identifier). It's unnecessary to check for uniqueness as uniqueness is the purpose of GUID's.

The total number of unique keys is 2128 or 3.4×1038. This number is so large that the probability of the same number being generated randomly twice is negligible.

Quote taken from Wikipedia

like image 3
James Hill Avatar answered Nov 15 '22 00:11

James Hill