Skip to content

Instantly share code, notes, and snippets.

@shoter
Created May 24, 2023 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoter/4d8769c5948d9bd8eef6771f167d371c to your computer and use it in GitHub Desktop.
Save shoter/4d8769c5948d9bd8eef6771f167d371c to your computer and use it in GitHub Desktop.
String Interpolation vs String Builder exception throwing benchmark
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
}
}
}
@shoter
Copy link
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