Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active August 19, 2021 06:44
Show Gist options
  • Save guitarrapc/529367010ba976cb10920e1ca15a0c59 to your computer and use it in GitHub Desktop.
Save guitarrapc/529367010ba976cb10920e1ca15a0c59 to your computer and use it in GitHub Desktop.
Even should not use mod.
void Main()
{
var summary = BenchmarkRunner.Run<BenchmarkEven>();
}
[BenchmarkDotNet.Attributes.MemoryDiagnoser]
public class BenchmarkEven
{
[Benchmark]
[Arguments(42)]
public bool IsEven(int i) => i % 2 == 0;
[Benchmark]
[Arguments(42)]
public bool IsEven2(int i) => (i & 1) == 0;
}

// * Summary *

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19043.1165 (21H1/May2021Update) AMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores .NET SDK=5.0.400 [Host] : .NET 5.0.9 (5.0.921.35908), X64 RyuJIT

Method i Mean Error StdDev Allocated
IsEven 42 0.1749 ns 0.0056 ns 0.0052 ns -
IsEven2 42 0.0000 ns 0.0000 ns 0.0000 ns -
@guitarrapc
Copy link
Author

from: https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-6/

dotnet/runtime#45463. i % 2 == 0. The JIT can now transform that into code more like i & 1 == 0

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