Created
November 27, 2025 06:15
-
-
Save devops-school/3d97d2ee9a2a980a33f1a20f0df81852 to your computer and use it in GitHub Desktop.
BenchmarkDotNet: DOTNET Lab & Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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