Skip to content

Instantly share code, notes, and snippets.

@mgravell
Created April 26, 2024 11:47
Show Gist options
  • Save mgravell/0f9306681f3ae6bbff2ee4891783f303 to your computer and use it in GitHub Desktop.
Save mgravell/0f9306681f3ae6bbff2ee4891783f303 to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
BenchmarkRunner.Run<PunBench>();
[SimpleJob(RuntimeMoniker.Net48), SimpleJob(RuntimeMoniker.Net80)]
public class PunBench
{
const int OperationsPerInvoke = 512;
[Benchmark(OperationsPerInvoke = OperationsPerInvoke, Baseline = true)]
public uint MemoryMarshalRead()
{
uint total = 0;
for (int i = 0; i < 512; i++)
{
total += MemoryMarshal.Read<ushort>("\r\n"u8);
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public uint StaticReadonlyField()
{
uint total = 0;
for (int i = 0; i < 512; i++)
{
total += TheField;
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public uint PropertyGet()
{
uint total = 0;
for (int i = 0; i < 512; i++)
{
total += TheProperty;
}
return total;
}
internal static readonly ushort TheField = BitConverter.IsLittleEndian ? (ushort)0x0A0D : (ushort)0x0D0A;
private static ushort TheProperty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => BitConverter.IsLittleEndian ? (ushort)0x0A0D : (ushort)0x0D0A;
}
}
BenchmarkDotNet v0.13.12, Windows 11 (10.0.26100.1)
AMD Ryzen 9 7900X, 1 CPU, 24 logical and 12 physical cores
.NET SDK 8.0.203
[Host] : .NET 8.0.3 (8.0.324.11423), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
.NET 8.0 : .NET 8.0.3 (8.0.324.11423), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
.NET Framework 4.8 : .NET Framework 4.8.1 (4.8.9232.0), X64 RyuJIT VectorSize=256
| Method | Job | Runtime | Mean | Error | StdDev | Ratio | RatioSD |
|-------------------- |------------------- |------------------- |----------:|----------:|----------:|------:|--------:|
| MemoryMarshalRead | .NET 8.0 | .NET 8.0 | 0.2072 ns | 0.0028 ns | 0.0024 ns | 1.00 | 0.00 |
| StaticReadonlyField | .NET 8.0 | .NET 8.0 | 0.2065 ns | 0.0024 ns | 0.0023 ns | 1.00 | 0.01 |
| PropertyGet | .NET 8.0 | .NET 8.0 | 0.2039 ns | 0.0040 ns | 0.0049 ns | 0.99 | 0.03 |
| | | | | | | | |
| MemoryMarshalRead | .NET Framework 4.8 | .NET Framework 4.8 | 1.1606 ns | 0.0141 ns | 0.0132 ns | 1.00 | 0.00 |
| StaticReadonlyField | .NET Framework 4.8 | .NET Framework 4.8 | 0.2074 ns | 0.0021 ns | 0.0018 ns | 0.18 | 0.00 |
| PropertyGet | .NET Framework 4.8 | .NET Framework 4.8 | 0.3911 ns | 0.0076 ns | 0.0071 ns | 0.34 | 0.01 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment