Created
December 15, 2016 04:32
-
-
Save ReubenBond/01ab8cea36997bbb97bdc45ad15c54a5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.Text; | |
using System.Threading; | |
using OrleansBenchmarks.Serialization; | |
namespace OrleansBenchmarks | |
{ | |
using BenchmarkDotNet.Attributes; | |
[Config(typeof(SerializationBenchmarkConfig))] | |
public class PoolBenchmark | |
{ | |
private readonly ConcurrentBag<StringBuilder> concurrentBag = new ConcurrentBag<StringBuilder>(); | |
private readonly ThreadLocal<List<StringBuilder>> stackPool = new ThreadLocal<List<StringBuilder>>(() => new List<StringBuilder>()); | |
[ThreadStatic] | |
private static List<StringBuilder> tsPool; | |
private static List<StringBuilder> GetThreadStaticPool() => tsPool ?? (tsPool = new List<StringBuilder>()); | |
[Setup] | |
public void Setup() | |
{ | |
ReturnListPool(GetListPool()); | |
ReturnBag(GetBag()); | |
ReturnThreadStaticListPool(GetThreadStaticListPool()); | |
} | |
private StringBuilder GetListPool() | |
{ | |
var pool = stackPool.Value; | |
if (pool.Count > 0) | |
{ | |
var val = pool[pool.Count - 1]; | |
pool.RemoveAt(pool.Count - 1); | |
return val; | |
} | |
return new StringBuilder(); | |
} | |
private void ReturnListPool(StringBuilder value) | |
{ | |
stackPool.Value.Add(value); | |
} | |
private StringBuilder GetThreadStaticListPool() | |
{ | |
var pool = GetThreadStaticPool(); | |
if (pool.Count > 0) | |
{ | |
var last = pool.Count - 1; | |
var val = pool[last]; | |
pool.RemoveAt(last); | |
return val; | |
} | |
return new StringBuilder(); | |
} | |
private void ReturnThreadStaticListPool(StringBuilder value) | |
{ | |
GetThreadStaticPool().Add(value); | |
} | |
private StringBuilder GetBag() | |
{ | |
StringBuilder result; | |
if (concurrentBag.TryTake(out result)) return result; | |
return new StringBuilder(); | |
} | |
private void ReturnBag(StringBuilder value) | |
{ | |
concurrentBag.Add(value); | |
} | |
[Benchmark] | |
public void ConcurrentBagPool() | |
{ | |
var val = GetBag(); | |
ReturnBag(val); | |
} | |
[Benchmark] | |
public void ThreadLocalListPool() | |
{ | |
var val = GetListPool(); | |
ReturnListPool(val); | |
} | |
[Benchmark] | |
public void ThreadStaticListPool() | |
{ | |
var val = GetThreadStaticListPool(); | |
ReturnThreadStaticListPool(val); | |
} | |
} | |
} |
Author
ReubenBond
commented
Dec 15, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment