Skip to content

Instantly share code, notes, and snippets.

@seldoff
Created May 16, 2025 10:49
Show Gist options
  • Select an option

  • Save seldoff/9bcec87b89279eb42aa1bde97b8fa16f to your computer and use it in GitHub Desktop.

Select an option

Save seldoff/9bcec87b89279eb42aa1bde97b8fa16f to your computer and use it in GitHub Desktop.
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace ConsoleApp3;
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<Bench>();
}
}
[MemoryDiagnoser]
public class Bench
{
public ulong Part0 = (ulong)Random.Shared.NextInt64();
public ulong Part1 = (ulong)Random.Shared.NextInt64();
public ulong Part2 = (ulong)Random.Shared.NextInt64();
public ulong Part3 = (ulong)Random.Shared.NextInt64();
[Benchmark]
public string Interpolation()
{
return $"{this.Part0:x16}{this.Part1:x16}{this.Part2:x16}{this.Part3:x16}";
}
[Benchmark]
public string StringBuilder()
{
var sb = new StringBuilder(64);
sb.Append(this.Part0.ToString("x16"));
sb.Append(this.Part1.ToString("x16"));
sb.Append(this.Part2.ToString("x16"));
sb.Append(this.Part3.ToString("x16"));
return sb.ToString();
}
[Benchmark]
public string StringConcat()
{
return string.Concat(
this.Part0.ToString("x16"),
this.Part1.ToString("x16"),
this.Part2.ToString("x16"),
this.Part3.ToString("x16"));
}
[Benchmark]
public ReadOnlySpan<char> CharArr()
{
var hash = new char[64];
var index = 0;
this.Part0.TryFormat(hash.AsSpan(index), out var bytesWritten, "x16");
index += bytesWritten;
this.Part1.TryFormat(hash.AsSpan(index), out bytesWritten, "x16");
index += bytesWritten;
this.Part2.TryFormat(hash.AsSpan(index), out bytesWritten, "x16");
index += bytesWritten;
this.Part3.TryFormat(hash.AsSpan(index), out bytesWritten, "x16");
return hash.AsSpan();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment