Skip to content

Instantly share code, notes, and snippets.

@aannenko
Created December 13, 2025 13:30
Show Gist options
  • Select an option

  • Save aannenko/8c928eff3bec67903d8026ac6c95870a to your computer and use it in GitHub Desktop.

Select an option

Save aannenko/8c928eff3bec67903d8026ac6c95870a to your computer and use it in GitHub Desktop.
Benchmark multiple Guid-to-Base64Url and Base64Url-to-Guid methods
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net10.0;net9.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
</ItemGroup>
</Project>
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Running;
using System.Buffers.Text;
// dotnet run -c Release -f net9.0 --filter "*" --runtimes net9.0 net10.0
BenchmarkRunner.Run<GuidToBase64Url>(args: args);
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[MemoryDiagnoser]
[HideColumns("Job", "Error", "StdDev", "Gen0")]
public class GuidToBase64Url
{
public Guid _guid = new("c05d4d42-e4e7-4f2e-9b1f-f896a86ed633");
public string _str = "Qk1dwOfkLk-bH_iWqG7WMw";
[BenchmarkCategory("to"), Benchmark(Baseline = true)]
public string ToShortString_Original()
{
return Convert.ToBase64String(_guid.ToByteArray())[..^2]
.Replace('+', '-')
.Replace('/', '_');
}
[BenchmarkCategory("to"), Benchmark]
public string ToShortString_Custom()
{
Span<byte> bytes = stackalloc byte[16];
_guid.TryWriteBytes(bytes);
Span<char> chars = stackalloc char[24];
Convert.TryToBase64Chars(bytes, chars, out _);
chars = chars[..22];
chars.Replace('+', '-');
chars.Replace('/', '_');
return chars.ToString();
}
[BenchmarkCategory("to"), Benchmark]
public string ToShortString_Base64Url()
{
Span<byte> bytes = stackalloc byte[16];
_guid.TryWriteBytes(bytes);
return Base64Url.EncodeToString(bytes);
}
[BenchmarkCategory("from"), Benchmark(Baseline = true)]
public Guid FromShortString_Original()
{
return new Guid(Convert.FromBase64String(
_str.Replace('_', '/').Replace('-', '+') + "=="));
}
[BenchmarkCategory("from"), Benchmark]
public Guid FromShortString_Custom()
{
Span<char> chars = stackalloc char[24];
_str.CopyTo(chars);
chars.Replace('_', '/');
chars.Replace('-', '+');
"==".CopyTo(chars[22..]);
Span<byte> bytes = stackalloc byte[16];
Convert.TryFromBase64Chars(chars, bytes, out _);
return new Guid(bytes);
}
[BenchmarkCategory("from"), Benchmark]
public Guid FromShortString_Base64Url()
{
Span<byte> bytes = stackalloc byte[16];
Base64Url.DecodeFromChars(_str.AsSpan(), bytes);
return new Guid(bytes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment