Skip to content

StackPool

Provides a shared pool of Stack<T> instances to reduce allocations.

C# Signature
internal static class StackPool<T>

The following example uses a pooled stack to process values in reverse order.

C#
using System.Collections.Generic;
using Hertzole.SourceGen;
public static class ReverseProcessor
{
public static void Process(IEnumerable<int> values)
{
// The scope returns the stack to the pool when disposed.
using (StackPool<int>.Get(out Stack<int> stack))
{
foreach (int value in values)
{
stack.Push(value);
}
while (stack.Count > 0)
{
System.Console.WriteLine(stack.Pop());
}
}
}
}

Retrieves a Stack<T> from the pool.

C# Signature
public static Stack<T> Get();

A Stack<T> from the pool.

Retrieves a Stack<T> from the pool and wraps it in a disposable scope that returns it automatically.

C# Signature
public static PoolScope<Stack<T>> Get(out Stack<T> item);

When this method returns, contains the Stack<T> retrieved from the pool.

A disposable scope that returns the Stack<T> to the pool when disposed.

Returns a Stack<T> to the pool.

C# Signature
public static void Return(Stack<T> item);

The Stack<T> to return to the pool.