using BenchmarkDotNet.Attributes; using System.Text; namespace Benchmarks.Console.Memory; [MemoryDiagnoser] public class Utf8Strings { private const string Dummy32 = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; private const string Dummy64 = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; private const string Dummy128 = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; private readonly MemoryStream _stream = new(1_024); [Benchmark] public ReadOnlySpan GetUtf8Value_32_u16const() { return Encoding.UTF8.GetBytes(Dummy32); } [Benchmark] public ReadOnlySpan GetUtf8Value_32_u8const() { return "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"u8; } [Benchmark] public ReadOnlySpan GetUtf8Value_64_u16const() { return Encoding.UTF8.GetBytes(Dummy64); } [Benchmark] public ReadOnlySpan GetUtf8Value_64_u8const() { return "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"u8; } [Benchmark] public ReadOnlySpan GetUtf8Value_128_u16const() { return Encoding.UTF8.GetBytes(Dummy128); } [Benchmark] public ReadOnlySpan GetUtf8Value_128_u8const() { return "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"u8; } [Benchmark] [ArgumentsSource(nameof(GetAuthValues))] public void WriteAuthHeaderToStream_u16const(string value) { var authHeaderName = Encoding.UTF8.GetBytes("Authorization: "); var authHeaderValue = Encoding.UTF8.GetBytes(value); _stream.Seek(0, SeekOrigin.Begin); // Prevent OutOfMemoryException when running the benchmark (which obviously not reinstantiates the class for each run) _stream.Write(authHeaderName.AsSpan()); _stream.Write(authHeaderValue.AsSpan()); } [Benchmark] [ArgumentsSource(nameof(GetAuthValues))] public void WriteAuthHeaderToStream_u8const(string value) { var authHeaderValue = Encoding.UTF8.GetBytes(value); _stream.Seek(0, SeekOrigin.Begin); // Prevent OutOfMemoryException when running the benchmark (which obviously not reinstantiates the class for each run) _stream.Write("Authorization: "u8); _stream.Write(authHeaderValue.AsSpan()); } public static IEnumerable GetAuthValues() { yield return new object[] { Dummy32 }; yield return new object[] { Dummy64 }; yield return new object[] { Dummy128 }; } }