Timing code with DateTime.Now is inaccurate. BenchmarkDotNet runs proper benchmarks with statistical analysis.
Install:
dotnet add package BenchmarkDotNet
Create Benchmark:
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
[MemoryDiagnoser]
public class StringBenchmarks
{
[Benchmark]
public string StringConcat()
{
string result = "";
for (int i = 0; i < 1000; i++)
result += i.ToString();
return result;
}
[Benchmark]
public string StringBuilder()
{
var sb = new System.Text.StringBuilder();
for (int i = 0; i < 1000; i++)
sb.Append(i);
return sb.ToString();
}
}
// Run benchmarks
BenchmarkRunner.Run();
Output:
| Method | Mean | Allocated | |-------------- |----------:|-----------:| | StringConcat | 183.2 μs | 2.01 MB | | StringBuilder | 15.3 μs | 20.5 KB |
StringBuilder is 12x faster with 100x less allocation!
Attributes: [Benchmark], [MemoryDiagnoser], [Params(…)], [GlobalSetup]
