Last active
February 10, 2025 18:18
-
-
Save davepcallan/d8f492b47956fa1e518f15eb1f06ae09 to your computer and use it in GitHub Desktop.
Simple string concat benchmark showing how to get started with BenchmarkDotNet and how to set some basic config
This file contains 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.Columns; | |
using BenchmarkDotNet.Configs; | |
using BenchmarkDotNet.Jobs; | |
using BenchmarkDotNet.Reports; | |
using System.Text; | |
namespace Benchmarks; | |
[MemoryDiagnoser] | |
[HideColumns(Column.RatioSD, Column.AllocRatio, Column.Gen0, Column.Gen2)] | |
[SimpleJob(RuntimeMoniker.Net90)] | |
[ReturnValueValidator(failOnError: true)] // Validate methods are equivalent | |
[Config(typeof(Config))] // Custom class to configure BenchmarkDotNet | |
public class StringBuilderVPlus | |
{ | |
private class Config : ManualConfig | |
{ | |
public Config() | |
{ | |
SummaryStyle = | |
SummaryStyle.Default | |
.WithRatioStyle(RatioStyle.Trend) | |
.WithTimeUnit(Perfolizer.Horology.TimeUnit.Nanosecond); | |
} | |
} | |
[Params(10, 20)] // Run benchmarks with these parameters | |
public int Concats; | |
[Benchmark] | |
public string StringBuilder() | |
{ | |
StringBuilder stringBuilder = new StringBuilder(); | |
for (int i = 0; i < Concats; i++) | |
{ | |
stringBuilder.Append("Hello World"); | |
} | |
return stringBuilder.ToString(); | |
} | |
[Benchmark(Baseline = true)] | |
public string StringConcatenation() | |
{ | |
string str = ""; | |
for (int i = 0; i < Concats; i++) | |
{ | |
str += "Hello World"; | |
} | |
return str; | |
} | |
} | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<StringBuilderVPlus>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment