Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davepcallan/cb56971502e910a888a0894784f137bb to your computer and use it in GitHub Desktop.
Save davepcallan/cb56971502e910a888a0894784f137bb to your computer and use it in GitHub Desktop.
String interpolation v string.join v string.create for concatenation of a few strings
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Reports;
using System;
namespace BenchmarkDotNet.Samples
{
[MemoryDiagnoser]
[Config(typeof(Config))]
[SimpleJob(RuntimeMoniker.Net80)]
[HideColumns(Column.Job, Column.RatioSD, Column.AllocRatio)]
public class StringCreateSimpleConcatBenchmarks
{
private class Config : ManualConfig
{
public Config()
{
SummaryStyle =
SummaryStyle.Default.WithRatioStyle(RatioStyle.Percentage);
}
}
private string
title = "Mr.", firstName = "David", middleName = "Patrick", lastName = "Callan";
[Benchmark]
public string StringInterpolation()
{
return
$"{title} {firstName} {middleName} {lastName}";
}
[Benchmark]
public string StringJoin()
{
return string.Join(" ", title, firstName,
middleName, lastName);
}
[Benchmark(Baseline = true)]
public string StringCreate()
{
return string.Create(title.Length + firstName.Length + middleName.Length + lastName.Length + 3,
(title, firstName, middleName, lastName),
(span, state) =>
{
state.title.AsSpan().CopyTo(span);
span = span.Slice(state.title.Length);
span[0] = ' ';
span = span.Slice(1);
state.firstName.AsSpan().CopyTo(span);
span = span.Slice(state.firstName.Length);
span[0] = ' ';
span = span.Slice(1);
state.middleName.AsSpan().CopyTo(span);
span = span.Slice(state.middleName.Length);
span[0] = ' ';
span = span.Slice(1);
state.lastName.AsSpan().CopyTo(span);
}
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment