Skip to content

Instantly share code, notes, and snippets.

@devops-school
Created November 27, 2025 06:15
Show Gist options
  • Select an option

  • Save devops-school/3d97d2ee9a2a980a33f1a20f0df81852 to your computer and use it in GitHub Desktop.

Select an option

Save devops-school/3d97d2ee9a2a980a33f1a20f0df81852 to your computer and use it in GitHub Desktop.
BenchmarkDotNet: DOTNET Lab & Demo
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace BenchmarkDotNetLab
{
[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
[RankColumn]
public class AsyncBenchmarks
{
// Simulate CPU-bound work (e.g., Fibonacci)
[MethodImpl(MethodImplOptions.NoInlining)]
private static int Fibonacci(int n)
{
if (n <= 1) return n;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
// Pure sync CPU-bound
[Benchmark(Baseline = true)]
public int Fibonacci_Sync() => Fibonacci(20);
// BAD PATTERN: wrapping CPU-bound in Task.Run just to make it async
[Benchmark]
public Task<int> Fibonacci_TaskRun()
=> Task.Run(() => Fibonacci(20));
// Simulated I/O: using Task.Delay
[Benchmark]
public async Task<int> SimulatedIo_Task()
{
await Task.Delay(10).ConfigureAwait(false);
return 42;
}
// Same "I/O" but returning ValueTask to reduce overhead
[Benchmark]
public async ValueTask<int> SimulatedIo_ValueTask()
{
await Task.Delay(10).ConfigureAwait(false);
return 42;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment