Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Last active February 10, 2025 18:18

Revisions

  1. davepcallan revised this gist Feb 10, 2025. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion GettingStartedWithBenchmarkDotNet.cs
    Original file line number Diff line number Diff line change
    @@ -21,7 +21,7 @@ public Config()
    SummaryStyle =
    SummaryStyle.Default
    .WithRatioStyle(RatioStyle.Trend)
    .WithTimeUnit(Perfolizer.Horology.TimeUnit.Millisecond);
    .WithTimeUnit(Perfolizer.Horology.TimeUnit.Nanosecond);
    }
    }

  2. davepcallan created this gist Feb 10, 2025.
    64 changes: 64 additions & 0 deletions GettingStartedWithBenchmarkDotNet.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    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.Millisecond);
    }
    }

    [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>();
    }
    }