Created
July 22, 2023 10:09
-
-
Save davepcallan/26c6d2fcd1f00fcbdb5cfe447d156aee to your computer and use it in GitHub Desktop.
String.Create v String.Join for simple string concat
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.Columns; | |
using BenchmarkDotNet.Configs; | |
using BenchmarkDotNet.Environments; | |
using BenchmarkDotNet.Jobs; | |
using BenchmarkDotNet.Reports; | |
using System; | |
using System.Text; | |
namespace BenchmarkDotNet.Samples | |
{ | |
[MemoryDiagnoser] | |
[Config(typeof(Config))] | |
[SimpleJob(RuntimeMoniker.Net80)] | |
[HideColumns(Column.Job, Column.RatioSD, Column.AllocRatio)] | |
public class StringJoinVStringCreateSimpleConcat | |
{ | |
private class Config : ManualConfig | |
{ | |
public Config() | |
{ | |
SummaryStyle = | |
SummaryStyle.Default.WithRatioStyle(RatioStyle.Percentage); | |
} | |
} | |
private string | |
title = "Mr.", firstName = "David", middleName = "Patrick", lastName = "Callan"; | |
[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); | |
} | |
); | |
} | |
[Benchmark] | |
public string StringConcat() | |
{ | |
return string. | |
Concat(new String[] { title, " ", firstName, " ", middleName, " ", lastName }); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment