Created
November 27, 2025 06:13
-
-
Save devops-school/b32680dde8d7ea5b9e60ada8459c5741 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.Text; | |
| namespace BenchmarkDotNetLab | |
| { | |
| [MemoryDiagnoser] | |
| [Orderer(SummaryOrderPolicy.FastestToSlowest)] | |
| [RankColumn] | |
| public class AllocationBenchmarks | |
| { | |
| [Params(100, 1000)] | |
| public int N; | |
| // Bad: repeatedly concatenating strings in a loop | |
| [Benchmark(Baseline = true)] | |
| public string StringConcat_PlusOperator() | |
| { | |
| string result = string.Empty; | |
| for (int i = 0; i < N; i++) | |
| { | |
| result += "Item" + i; // each concat allocates | |
| } | |
| return result; | |
| } | |
| // Better: use StringBuilder | |
| [Benchmark] | |
| public string StringConcat_StringBuilder() | |
| { | |
| var sb = new StringBuilder(); | |
| for (int i = 0; i < N; i++) | |
| { | |
| sb.Append("Item"); | |
| sb.Append(i); | |
| } | |
| return sb.ToString(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment