Skip to content

Instantly share code, notes, and snippets.

@mgravell
Created April 12, 2023 14:13
Show Gist options
  • Save mgravell/7ceb254006b229be79bcab3ecc65e07d to your computer and use it in GitHub Desktop.
Save mgravell/7ceb254006b229be79bcab3ecc65e07d to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Runtime.CompilerServices;
BenchmarkRunner.Run<SkipLocalsInitBenchmark>();
[SimpleJob]
public unsafe class SkipLocalsInitBenchmark
{
// example numbers taken from BCryptAlgorithmHandle.GetAlgorithmName
const int StackAllocCharSize = 128;
private static ReadOnlySpan<char> Payload => "hello, world";
[Benchmark(Baseline = true)]
public void WithInit()
{
Span<char> buffer = stackalloc char[StackAllocCharSize];
// just do *something* to justify the local
Payload.CopyTo(buffer);
}
[Benchmark, SkipLocalsInit]
public void SkipInit()
{
Span<char> buffer = stackalloc char[StackAllocCharSize];
// just do *something* to justify the local
Payload.CopyTo(buffer);
}
}
BenchmarkDotNet=v0.13.5, OS=Windows 11 (10.0.22621.1555/22H2/2022Update/SunValley2)
Intel Core i9-9900K CPU 3.60GHz (Coffee Lake), 1 CPU, 16 logical and 8 physical cores
.NET SDK=8.0.100-preview.1.23115.2
[Host] : .NET 8.0.0 (8.0.23.11008), X64 RyuJIT AVX2
DefaultJob : .NET 8.0.0 (8.0.23.11008), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev | Ratio |
|--------- |---------:|----------:|----------:|------:|
| WithInit | 7.396 ns | 0.1415 ns | 0.1324 ns | 1.00 |
| SkipInit | 2.804 ns | 0.0121 ns | 0.0101 ns | 0.38 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment