Last active
July 14, 2021 12:37
-
-
Save linkdotnet/df97d977319e281619c26563a1329c5a to your computer and use it in GitHub Desktop.
Benchmark string concat different approaches
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 System; | |
using System.Text; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace StringBuilderTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<StringBuilderBenchmark>(); | |
} | |
} | |
public class StringBuilderBenchmark | |
{ | |
[Params(2, 10, 50, 100)] public int ConcatSize { get; set; } | |
[Benchmark] | |
public string ConcatViaStringBuilder() | |
{ | |
var sb = new StringBuilder(); | |
for (var i = 0; i < ConcatSize; i++) | |
{ | |
sb.Append(i); | |
} | |
return sb.ToString(); | |
} | |
[Benchmark] | |
public string ConcatViaConcatBoxed() | |
{ | |
var output = string.Empty; | |
for (var i = 0; i < ConcatSize; i++) | |
{ | |
output += output + i; | |
} | |
return output; | |
} | |
[Benchmark] | |
public string ConcatViaConcatUnboxed() | |
{ | |
var output = string.Empty; | |
for (var i = 0; i < ConcatSize; i++) | |
{ | |
output += output + i.ToString(); | |
} | |
return output; | |
} | |
[Benchmark] | |
public string ConcatViaStringFormatBoxed() | |
{ | |
var output = string.Empty; | |
for (var i = 0; i < ConcatSize; i++) | |
{ | |
output = $"{output}{i}"; | |
} | |
return output; | |
} | |
[Benchmark] | |
public string ConcatViaStringFormatUnboxed() | |
{ | |
var output = string.Empty; | |
for (var i = 0; i < ConcatSize; i++) | |
{ | |
output = $"{output}{i.ToString()}"; | |
} | |
return output; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment