Skip to content

Instantly share code, notes, and snippets.

@idea-lei
Last active February 18, 2025 10:27
Show Gist options
  • Save idea-lei/8b619c1b46ed2158c2920a172a644c7f to your computer and use it in GitHub Desktop.
Save idea-lei/8b619c1b46ed2158c2920a172a644c7f to your computer and use it in GitHub Desktop.
High performance Short Id
/// <summary>
/// High Performance and thread-safe ShortId in string format, preferred when a GUID is overkill.
/// </summary>
/// <remarks>
/// Based on long type (64 bit), so max length is 13, not recommanded for fewer than 6 chars. (6-13, 8 as default)
/// </remarks>
public static class ShortId
{
/// <summary>
/// 32 chars (2^5) removed some chars for better readablity
/// </summary>
private const string chars = "0123456789abcdefghjkmnpqrstvwxyz";
public static string New([Range(6, 13)] int size = 8) => FromRandom(size);
public static string FromDateTime([Range(6, 13)] int size = 8)
=> ToString(size, DateTime.Now.Ticks);
public static string FromRandom([Range(6, 13)] int size = 8)
=> ToString(size, unchecked((long)Random.Shared.Next(int.MaxValue) * Random.Shared.Next(int.MaxValue)));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static string ToString(int size, long value)
{
var output = new char[size];
for (int i = size - 1; i >= 0; i--)
{
output[i] = chars[(int)(value % 32)];
value >>= 5;
}
return new string(output);
}
}
// **Benchmarks (each 1000 generations)**
//| Method | Mean | Error | StdDev | Gen0 | Allocated |
//|------------- |---------:|---------:|---------:|--------:|----------:|
//| NewGuid | 87.70 us | 1.702 us | 2.272 us | 20.3857 | 93.75 KB |
//| FromDateTime | 97.66 us | 1.116 us | 0.989 us | 16.9678 | 78.13 KB |
//| FromRandom | 45.05 us | 0.656 us | 0.582 us | 16.9678 | 78.13 KB |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment