Skip to content

Instantly share code, notes, and snippets.

@BenjaminAbt
Created October 29, 2021 20:06
Show Gist options
  • Save BenjaminAbt/073749333317eaaf6ca1b8cbae67c859 to your computer and use it in GitHub Desktop.
Save BenjaminAbt/073749333317eaaf6ca1b8cbae67c859 to your computer and use it in GitHub Desktop.
.NET 6 - StringBuilder vs. String Builder ObjectPool
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.ObjectPool;
namespace Benchmarks;
[MemoryDiagnoser]
public class Benchmark
{
private List<string> _data;
//.NET Core SDK=6.0.100-rc.2.21505.57
// [Host] : .NET Core 6.0.0 (CoreCLR 6.0.21.48005, CoreFX 6.0.21.48005), X64 RyuJIT
// DefaultJob : .NET Core 6.0.0 (CoreCLR 6.0.21.48005, CoreFX 6.0.21.48005), X64 RyuJIT
//
// @abt_benjamin
//| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
//|--------------------- |---------:|----------:|----------:|-------:|-------:|------:|----------:|
//| StringBuilder_NoPool | 2.076 us | 0.0227 us | 0.0212 us | 2.2202 | 0.2747 | - | 37200 B |
//| StringBuilder_Pooled | 1.130 us | 0.0076 us | 0.0067 us | - | - | - | - |
[GlobalSetup]
public void GlobalSetup()
{
_data = Enumerable.Range(0, 200)
.Select(x => new string('a', 80)).ToList();
_sbPool = ObjectPool.Create<StringBuilder>();
}
[Benchmark]
public void StringBuilder_NoPool()
{
StringBuilder sb = new();
foreach (var entry in _data)
{
var e = entry;
sb.Append(e);
}
}
private ObjectPool<StringBuilder> _sbPool;
[Benchmark]
public void StringBuilder_Pooled()
{
StringBuilder sb = _sbPool.Get();
foreach (var entry in _data)
{
var e = entry;
sb.Append(e);
}
sb.Clear();
_sbPool.Return(sb);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment