Skip to content

Instantly share code, notes, and snippets.

@EgorBo
Created November 1, 2019 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EgorBo/79090d082655c49a0cff1c16da53b73d to your computer and use it in GitHub Desktop.
Save EgorBo/79090d082655c49a0cff1c16da53b73d to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public class Program
{
static void Main(string[] args)
{
// I used .NET Core 3.1 + BDN 0.12.0
BenchmarkRunner.Run<Program>();
}
private static bool AlwaysFalseProp { get; } = SetupField();
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool SetupField()
{
return false;
}
[Benchmark(Baseline = true)]
public double Foo0()
{
return Math.Sqrt(42);
}
[Benchmark]
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public double Foo1()
{
if (AlwaysFalseProp)
{
Console.WriteLine();
throw new Exception("unreachable");
}
return Math.Sqrt(42);
}
[Benchmark]
public double Foo2()
{
if (AlwaysFalseProp)
{
Console.WriteLine();
throw new Exception("unreachable");
}
return Math.Sqrt(42);
}
}
/*
| Method | Mean | Error | StdDev | Ratio | RatioSD |
|------- |----------:|----------:|----------:|-------:|--------:|
| Foo0 | 0.0103 ns | 0.0026 ns | 0.0023 ns | 1.00 | 0.00 |
| Foo1 | 1.0871 ns | 0.0014 ns | 0.0013 ns | 110.79 | 24.92 |
| Foo2 | 0.0230 ns | 0.0021 ns | 0.0017 ns | 2.49 | 0.61 |
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment