Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save devops-school/b32680dde8d7ea5b9e60ada8459c5741 to your computer and use it in GitHub Desktop.
BenchmarkDotNet: DOTNET Lab & Demo
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