Mirror Networking
Pool.cs
1// Pool to avoid allocations (from libuv2k)
2// API consistent with Microsoft's ObjectPool<T>.
3using System;
4using System.Collections.Generic;
5using System.Runtime.CompilerServices;
6
7namespace Mirror
8{
9 public class Pool<T>
10 {
11 // Mirror is single threaded, no need for concurrent collections
12 readonly Stack<T> objects = new Stack<T>();
13
14 // some types might need additional parameters in their constructor, so
15 // we use a Func<T> generator
16 readonly Func<T> objectGenerator;
17
18 public Pool(Func<T> objectGenerator, int initialCapacity)
19 {
20 this.objectGenerator = objectGenerator;
21
22 // allocate an initial pool so we have fewer (if any)
23 // allocations in the first few frames (or seconds).
24 for (int i = 0; i < initialCapacity; ++i)
25 objects.Push(objectGenerator());
26 }
27
28 // DEPRECATED 2022-03-10
29 [Obsolete("Take() was renamed to Get()")]
30 public T Take() => Get();
31
32 // take an element from the pool, or create a new one if empty
33 [MethodImpl(MethodImplOptions.AggressiveInlining)]
34 public T Get() => objects.Count > 0 ? objects.Pop() : objectGenerator();
35
36 // return an element to the pool
37 [MethodImpl(MethodImplOptions.AggressiveInlining)]
38 public void Return(T item) => objects.Push(item);
39
40 // count to see how many objects are in the pool. useful for tests.
41 public int Count => objects.Count;
42 }
43}