If you need a unique ID, UUIDs provide a variety of options. It’s worth noting that variants 1, 2, and 7 all incorporate a timestamp into the UUID. In the case of variant 7, this has the benefit of making the UUID sortable, which can be convenient in many cases (v1/v2 incorporate a MAC address which means that they’re sortable if generated with the same NIC).
I bring this up because Dave inherited some code written by a “guru”. Said guru was working before UUIDv7 was a standard, but also didn’t have any problems that required sortable UUIDs, and thus had no real reason to use timestamp based UUIDs. They just needed some random identifier and, despite using C#, didn’t use the UUID functions built in to the framework. No, they instead did this:
string uniqueID = String.Format("{0:d9}", (DateTime.UtcNow.Ticks / 10) % 1000000000);
A Tick
is 100 nanoseconds. We divide that by ten, mod by a billion, and then call that our unique identifier.
This is, as you might guess, not unique. First there’s the possibility of timestamp collisions: generating two of these too close together in time would collide. Second, the math is just complete nonsense. We divide Ticks
by ten (converting hundreds of nanoseconds into thousands of nanoseconds), then we mod by a billion. So every thousand seconds we loop and have a risk of collision again?
Maybe, maybe, these are short-lived IDs and a thousand seconds is plenty of time. But even if that’s true, none of this is a good way to do that.
I suppose the saving grace is they use UtcNow
and not Now
, thus avoiding situations where collisions also happen because of time zones?
BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!