forked from laicasaane/unity-supplements
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArray1Pool{T}.cs
91 lines (73 loc) · 2.09 KB
/
Array1Pool{T}.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System.Collections.Generic;
namespace System.Collections.Pooling
{
public static class Array1Pool<T>
{
private static readonly PoolMap _poolMap = new PoolMap();
public static T[] Get(int size)
=> Get((long)size);
public static T[] Get(long size)
{
if (size < 0)
throw new ArgumentOutOfRangeException(nameof(size), "Must be a positive number.");
if (_poolMap.TryGetValue(size, out var pool))
{
if (pool.Count > 0)
return pool.Dequeue();
}
else
{
_poolMap.Add(size, new Queue<T[]>());
}
return new T[size];
}
public static void Return(T[] item)
{
if (item == null)
return;
item.Clear();
Return(item.LongLength, item);
}
public static void Return(params T[][] items)
{
if (items == null)
return;
foreach (var item in items)
{
if (item == null)
continue;
item.Clear();
Return(item.LongLength, item);
}
}
public static void Return(IEnumerable<T[]> items)
{
if (items == null)
return;
foreach (var item in items)
{
if (item == null)
continue;
item.Clear();
Return(item.LongLength, item);
}
}
private static void Return(long size, T[] item)
{
if (!_poolMap.TryGetValue(size, out var pool))
{
_poolMap.Add(size, pool = new Queue<T[]>());
}
pool.Enqueue(item);
}
public static void Clear()
{
foreach (var kv in _poolMap)
{
kv.Value.Clear();
}
_poolMap.Clear();
}
private class PoolMap : Dictionary<long, Queue<T[]>> { }
}
}