Skip to content

Instantly share code, notes, and snippets.

@NWoodsman
Created August 27, 2025 02:08
Show Gist options
  • Save NWoodsman/8982055c438b704072e22e0741d84293 to your computer and use it in GitHub Desktop.
Save NWoodsman/8982055c438b704072e22e0741d84293 to your computer and use it in GitHub Desktop.
Benchmark of 8 byte struct eqality
using System.Runtime.Intrinsics;
using BenchmarkDotNet.Attributes;
namespace Benchmarks.ByteEquality;
public struct Foo
{
public byte B1, B2, B3, B4, B5, B6, B7, B8;
public readonly bool Equals1(Foo other)
{
return B1 == other.B1 && B2 == other.B2 && B3 == other.B3 && B4 == other.B4 && B5 == other.B5 && B6 == other.B6 && B7 == other.B7 && B8 == other.B8;
}
public readonly bool Equals_Ref(ref Foo other)
{
return B1 == other.B1 && B2 == other.B2 && B3 == other.B3 && B4 == other.B4 && B5 == other.B5 && B6 == other.B6 && B7 == other.B7 && B8 == other.B8;
}
public readonly bool Equals_Vec(ref Foo other)
{
if (Vector64.IsHardwareAccelerated)
{
Vector64<byte> left = Vector64.Create(B1, B2, B3, B4, B5, B6, B7, B8);
Vector64<byte> right = Vector64.Create(other.B1, other.B2, other.B3, other.B4, other.B5, other.B6, other.B7, other.B8);
return left == right;
}
else return Equals_Ref(ref other);
}
}
public class BenchmarkByteEquals
{
public int TestInt { get; set; } = 1000;
public Foo[] Foo1 { get; set; }
public Foo[] Foo2 { get; set; }
[GlobalSetup]
public void Setup()
{
Random r = new Random();
Foo1 = new Foo[TestInt];
Foo2 = new Foo[TestInt];
for(int i = 0; i < TestInt; i++)
{
Foo1[i] = new Foo
{
B1= (byte)r.Next(),
B2 = (byte)r.Next(),
B3 = (byte)r.Next(),
B4 = (byte)r.Next(),
B5 = (byte)r.Next(),
B6 = (byte)r.Next(),
B7 = (byte)r.Next(),
B8 = (byte)r.Next(),
};
Foo2[i] = new Foo
{
B1 = (byte)r.Next(),
B2 = (byte)r.Next(),
B3 = (byte)r.Next(),
B4 = (byte)r.Next(),
B5 = (byte)r.Next(),
B6 = (byte)r.Next(),
B7 = (byte)r.Next(),
B8 = (byte)r.Next(),
};
}
}
[Benchmark]
public bool Benchmark_Equals()
{
bool b = false;
for(int i = 0;i < TestInt; i++)
{
Foo f1 = Foo1[i];
Foo f2 = Foo2[i];
b = f1.Equals(f2);
}
return b;
}
[Benchmark]
public bool Benchmark_Ref()
{
bool b = false;
for (int i = 0; i < TestInt; i++)
{
Foo f1 = Foo1[i];
Foo f2 = Foo2[i];
b = f1.Equals_Ref(ref f2);
}
return b;
}
[Benchmark]
public bool Benchmark_Vec()
{
bool b = false;
for (int i = 0; i < TestInt; i++)
{
Foo f1 = Foo1[i];
Foo f2 = Foo2[i];
b = f1.Equals_Vec(ref f2);
}
return b;
}
}
@NWoodsman
Copy link
Author

Benchmark results: (Core i7-12700K)

Method Mean Error StdDev
Benchmark_Equals 7,155.9 ns 108.68 ns 101.66 ns
Benchmark_Ref 773.5 ns 13.96 ns 13.05 ns
Benchmark_Vec 748.8 ns 13.84 ns 12.94 ns

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment