Skip to content

Instantly share code, notes, and snippets.

@asimmon
Created October 8, 2021 14:31
Show Gist options
  • Save asimmon/4afa0520e72d92ea578a2c0faff591b5 to your computer and use it in GitHub Desktop.
Save asimmon/4afa0520e72d92ea578a2c0faff591b5 to your computer and use it in GitHub Desktop.
Await benchmarks
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
var benchmarkOptions = DefaultConfig.Instance.WithSummaryStyle(SummaryStyle.Default.WithRatioStyle(RatioStyle.Trend));
_ = BenchmarkRunner.Run<AwaitBenchmarks>(benchmarkOptions);
public class AwaitBenchmarks
{
[Benchmark(Baseline = true)]
public async Task WithoutAwaits() => await WithoutAwaitMethod1();
[Benchmark]
public async Task WithAwaits() => await WithAwaitMethod1();
private static Task WithoutAwaitMethod1() => WithoutAwaitMethod2();
private static Task WithoutAwaitMethod2() => WithoutAwaitMethod3();
private static Task WithoutAwaitMethod3() => MyAsyncMethod();
private static async Task WithAwaitMethod1() => await WithAwaitMethod2();
private static async Task WithAwaitMethod2() => await WithAwaitMethod3();
private static async Task WithAwaitMethod3() => await MyAsyncMethod();
private static async Task MyAsyncMethod() => await Task.Yield();
}
| Method | Mean | Error | StdDev | Ratio | RatioSD |
|-------------- |-----------:|--------:|--------:|-------------:|--------:|
| WithoutAwaits | 834.4 ns | 4.62 ns | 4.32 ns | baseline | |
| WithAwaits | 1,037.8 ns | 7.25 ns | 6.79 ns | 1.24x slower | 0.01x |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment