Skip to content

Instantly share code, notes, and snippets.

@shoter
Created May 24, 2023 11:47
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/a303d331839d11c8d838b882ddd5cccf to your computer and use it in GitHub Desktop.
Save shoter/a303d331839d11c8d838b882ddd5cccf to your computer and use it in GitHub Desktop.
string interp vs building higher nesting
using System;
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
var summary = BenchmarkRunner.Run<StringBenchmark>();
[MemoryDiagnoser]
public class StringBenchmark
{
private const string testVariable = "test";
[Benchmark]
public void BenchmarkStringInterpolation()
{
TryCatchMethod(() => RecursiveMethodInterpolation(20));
}
[Benchmark]
public void BenchmarkStringBuilder()
{
TryCatchMethod(() => RecursiveMethodStringBuilder(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 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);
}
}
@shoter
Copy link
Author

shoter commented May 24, 2023

Method Mean Error StdDev Gen0 Allocated
BenchmarkStringInterpolation 11.24 us 0.201 us 0.188 us 0.4730 3.95 KB
BenchmarkStringBuilder 12.30 us 0.231 us 0.428 us 0.5341 4.4 KB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment