Skip to content

Instantly share code, notes, and snippets.

@dadhi
Created June 12, 2018 12:48
Show Gist options
  • Save dadhi/62299270654e8c11a24eaa887d9817f6 to your computer and use it in GitHub Desktop.
Save dadhi/62299270654e8c11a24eaa887d9817f6 to your computer and use it in GitHub Desktop.
Stack based object pool C# .NET tailored for performance and simplicity
using System;
using System.Threading;
using static System.Console;
public class Test
{
public static void Main()
{
var p = new StackPool<S>();
var s1 = Rent(p, "55");
WriteLine(s1);
var s2 = Rent(p, "66");
WriteLine(s2);
p.Return(s1);
WriteLine("returning "+s1);
p.Return(s2);
WriteLine("returning "+s2);
var s3 = Rent(p, "77");
WriteLine(s3);
}
private static S Rent(StackPool<S> p, string s) =>
p.Rent()?.Init(s) ?? new S(s);
public class S
{
public static int N;
private string _s;
public S Init(string s)
{ _s = s; return this; }
public S(string s) { _s = s; ++N; }
public override string ToString() =>
_s+"("+N+")";
}
}
public sealed class StackPool<T> where T : class
{
public T Rent() =>
Interlocked.Exchange(ref _s, _s?.Tail)
?.Head;
public void Return(T x) =>
Interlocked.Exchange(ref _s,
new Stack(x, _s));
private Stack _s;
private sealed class Stack
{
public T Head;
public Stack Tail;
public Stack(T h, Stack t)
{
Head = h;
Tail = t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment