-
-
Save shoter/c3aa00c480a7f1b7f775c4110bc42de4 to your computer and use it in GitHub Desktop.
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; | |
var summary = BenchmarkRunner.Run<StringBenchmark>(); | |
[MemoryDiagnoser] | |
public class StringBenchmark | |
{ | |
private string testVariable = "test"; | |
public StringBenchmark() | |
{ | |
testVariable += Random.Shared.NextInt64(); | |
} | |
[Benchmark] | |
public void BenchmarkStringInterpolation() | |
{ | |
TryCatchMethod(() => RecursiveMethodInterpolation(20)); | |
} | |
[Benchmark] | |
public void BenchmarkStringBuilder() | |
{ | |
TryCatchMethod(() => RecursiveMethodStringBuilder(20)); | |
} | |
[Benchmark] | |
public void BenchmarkStringConc() | |
{ | |
TryCatchMethod(() => RecursiveMethodInterpolationConc(20)); | |
} | |
private void TryCatchMethod(Action action) | |
{ | |
try | |
{ | |
action(); | |
} | |
catch (Exception ex) | |
{ | |
string message = ex.Message; | |
string stackTrace = ex.StackTrace; | |
} | |
} | |
private void RecursiveMethodInterpolation(int depth) | |
{ | |
if(depth == 0) | |
{ | |
throw new Exception($"asdsadsad {testVariable} in element {testVariable} is not as my house"); | |
} | |
RecursiveMethodInterpolation(depth - 1); | |
} | |
private void RecursiveMethodInterpolationConc(int depth) | |
{ | |
if(depth == 0) | |
{ | |
throw new Exception("asdsadsad" + testVariable + $"in element {testVariable} is not as my house"); | |
} | |
RecursiveMethodInterpolationConc(depth - 1); | |
} | |
private void RecursiveMethodStringBuilder(int depth) | |
{ | |
if(depth == 0) | |
{ | |
StringBuilder stringBuilder = new StringBuilder(); | |
stringBuilder.Append("asdsadsad "); | |
stringBuilder.Append(testVariable); | |
stringBuilder.Append(" in element "); | |
stringBuilder.Append(testVariable); | |
stringBuilder.Append(" is not as my house"); | |
throw new Exception(stringBuilder.ToString()); | |
} | |
RecursiveMethodStringBuilder(depth - 1); | |
} | |
} |
Author
shoter
commented
May 24, 2023
Method | Mean | Error | StdDev | Gen0 | Allocated |
---|---|---|---|---|---|
BenchmarkStringInterpolation | 138.87 us | 2.754 us | 5.688 us | 2.9297 | 25.63 KB |
BenchmarkStringBuilder | 21.43 us | 0.426 us | 0.747 us | 0.4272 | 3.57 KB |
BenchmarkStringConc | 20.79 us | 0.410 us | 1.044 us | 0.3662 | 3.11 KB |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment