Created
May 24, 2023 11:39
-
-
Save shoter/4d8769c5948d9bd8eef6771f167d371c to your computer and use it in GitHub Desktop.
String Interpolation vs String Builder exception throwing benchmark
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>(); | |
public class StringBenchmark | |
{ | |
private const string testVariable = "test"; | |
[Benchmark] | |
public void BenchmarkStringInterpolation() | |
{ | |
try | |
{ | |
throw new Exception($"asdsadsad {testVariable} in element {testVariable} is not as my house"); | |
} | |
catch (Exception) | |
{ | |
// Here, we're not doing anything with the exception | |
// We just want to measure the performance of throwing it | |
} | |
} | |
[Benchmark] | |
public void BenchmarkStringBuilder() | |
{ | |
try | |
{ | |
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()); | |
} | |
catch (Exception) | |
{ | |
// Here, we're not doing anything with the exception | |
// We just want to measure the performance of throwing it | |
} | |
} | |
} |
Author
shoter
commented
May 24, 2023
•
Method | Mean | Error | StdDev |
---|---|---|---|
BenchmarkStringInterpolation | 4.264 us | 0.0836 us | 0.0821 us |
BenchmarkStringBuilder | 4.797 us | 0.0956 us | 0.1243 us |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment