Creating Uniques Ids on Elixir
We often need unique ids to generate dynamic and unique filenames or hashes for many purposes like URL validations, QR creations, etc. For that aim, we need to ensure that the “token” or hash is unique in our system.
A common way to face this is using the server time as an unrepeatable factor, though there are other random methods like UUID.
The first approach on Elixir could be using just the system time as filename. If you don’t mind that the filename contains only numbers, is the faster method.
Otherwise, if you come from PHP and are very nostalgic, or you prefer a longer and alphanumeric filename, you could hash it with MD5.
Of course, it is costly.
Other options?
As an alternative, you could consider UUID on any of its versions (though the benchmarks I did V3 and V5 were by far the winners). For this, you must include a library in your mix.exs
{:uuid, “~> 1.1”}
Finally, we have also the :crypto’s function strong_rand_bytes()/1 option:
You can see both UUID and strong_rand_bytes option below:
Results:
As we can see, the most affordable option is :os.system_time, which is by far faster than the rest. However, if it is used in massive contexts, the chances of generating two identical strings are higher. In that case, the most reliable alternative would be to jump to the third option UUID.V3, since it uses other variables besides the date to build the Unique ID, which makes a match in the obtained string almost impossible.