EgorBot / runtime-utils

MIT License
0 stars 1 forks source link

PGO issue with EqualityComparer #91

Open EgorBo opened 1 month ago

EgorBo commented 1 month ago

@EgorBot -intel -arm64 --runtimes net9.0

using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Collections.Generic;

BenchmarkRunner.Run<MyBenchmarks>(args: args);

public class MyBenchmarks
{
    [Benchmark] public bool Bench_SharedEquals() => SharedEquals("aaaaa", "aaaab");
    [Benchmark] public bool Bench_SharedEquals_specialized() => SharedEquals_specialized("aaaaa", "aaaab");

    // NoInlining simulates a large method in Dictionary (e.g. FindValue)
    // which is not inlined into an exact context (too big)
    [MethodImpl(MethodImplOptions.NoInlining)]
    static bool SharedEquals<T>(T t1, T t2) => 
        EqualityComparer<T>.Default.Equals(t1, t2);

    [MethodImpl(MethodImplOptions.NoInlining)]
    static bool SharedEquals_specialized<T>(T t1, T t2)
    {
        // JIT is expected to do the same for SharedEquals<T> with PGO, but it doesn't
        if (typeof(T) == typeof(string))
            return string.Equals(Unsafe.As<T, string>(ref t1), Unsafe.As<T, string>(ref t2));

        return EqualityComparer<T>.Default.Equals(t1, t2);
    }
}
EgorBot commented 1 month ago

Benchmark results on AzureAmpere

BenchmarkDotNet v0.14.0, Ubuntu 22.04.5 LTS (Jammy Jellyfish)
AzureAmpere
  Job-HQPNAX : .NET 9.0.0 (9.0.24.43107), Arm64 RyuJIT AdvSIMD
Runtime=.NET 9.0  Toolchain=net9.0
Method Mean Error
Bench_SharedEquals 8.692 ns 0.0159 ns
Bench_SharedEquals_specialized 5.417 ns 0.0079 ns

BDN_Artifacts.zip

EgorBot commented 1 month ago

Benchmark results on AzureIntel

BenchmarkDotNet v0.14.0, Ubuntu 22.04.5 LTS (Jammy Jellyfish)
Intel Xeon Platinum 8370C CPU 2.80GHz, 1 CPU, 4 logical and 2 physical cores
  Job-VEYOOV : .NET 9.0.0 (9.0.24.43107), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
Runtime=.NET 9.0  Toolchain=net9.0
Method Mean Error
Bench_SharedEquals 5.462 ns 0.0089 ns
Bench_SharedEquals_specialized 3.025 ns 0.0302 ns

BDN_Artifacts.zip

EgorBot commented 1 month ago

cc @EgorBo (logs)

EgorBot commented 1 month ago

cc @EgorBo (logs)