Share via


How to generate a GUID in 250K easy steps

A friend on my previous team wrote a tool to generate GUID values where the first two bytes are zero. (And I'll say right here that I don't think there is a legitimate need for such a tool, but that's not the point.) I'm working from memory but the C# code was something like:

public static Guid Generate()
{
   Guid guid = Guid.NewGuid();
   while (!guid.ToString().StartsWith("0000"))
   {
      guid = Guid.NewGuid();
   }
   return guid;
}

 

As I said, it was for a tool, and it would only get called once so the perf doesn't really matter; it gets the job done.  I just thought it was a pretty funny approach.  The friend in question was an excellent programmer, so I am going to blame it on too many limoncellos.  All I know is that now he's in law school.

 

Generating a GUID and just zeroing out the first two bytes (using ToByteArray and the appropriate Guid ctor) appears to be about 250,000 times faster.  That seems about right, if you think about it.