A shorter, more user-friendly GUID
When generating HTML code, you often need a unique identifier.
A GUID works fine but it is very long (3297F0F2-35D3-4231-919D-1CFCF4035975
).
You can shorten it but isn’t there a more optimized (faster) way
to generate an identifier in C#?
Here is a class containing several methods.
public class Identifier
{
private static Random _rnd = new Random();
// 8da18880a18a4cd
public string NewId_FromTicks() => DateTime.Now.Ticks.ToString("x");
// c9a646d3-9c61-4cb7-bfcd-ee2522c8f633
public string NewId_FromGuid() => Guid.NewGuid().ToString();
// 1WIXVZtbA0qKPcZ
public string NewId_FromGuidBase64() => Convert.ToBase64String(Guid.NewGuid().ToByteArray())
.Replace("/", "_")
.Replace("+", "-")
.Substring(0, 15);
// 1WIXVZtbA0qKPcZ
public string NewId_FromGuidShorted() => Guid.NewGuid().ToString("N").Substring(0, 15);
// 2c6fec62
public string NewId_FromRandomInt() => _rnd.Next(int.MaxValue).ToString("x");
// 127d9edf
public string NewId_FromRandomLong() => _rnd.Next().ToString("x");
// 127d9edf14385adb
public string NewId_FromRandomDoubleLong() => $"{_rnd.Next().ToString("x")}{_rnd.Next().ToString("x")}";
}
The following table shows the average execution time of these methods, using the benchmark library BenchmarkDotNet.
BenchmarkDotNet=v0.13.1, OS=Windows 8 (6.2.9200.556)
Intel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores
.NET SDK=6.0.201
[Host] : .NET 6.0.3 (6.0.322.12309), X64 RyuJIT
DefaultJob : .NET 6.0.3 (6.0.322.12309), X64 RyuJIT
| Method | Example | Mean |
|------------------|--------------------------------------|-----------|
| From Rnd Long: 10aad4a0 51.14 ns |
| From Rnd Int: 4a9d0f06 51.59 ns |
| From Rnd Long: 6aa977f03314e4b4 115.12 ns |
| From Ticks: 8da188a929219fab 174.41 ns |
| From Guid Base64: aRk3NU0b0ka04Oqc 206.67 ns |
| From Guid: 25ee3842-0c33-4a63-9b83-a7d1c0266809 224.59 ns |
| From Guid Shorted: 6ee0e232196b4a9 237.51 ns |
A good compromise is the use of the method NewId_FromRandomDoubleLong
.
which returns a value over 12 characters and much faster than the GUID.
This value is acceptable when generating identifiers from a web server
or a standalone application. It is still preferable to use a GUID when working
with several servers or data exchanges between clients.