Tanoda
ArrayPool.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using System;
10using System.Collections.Generic;
11using UnityEngine;
12
13namespace Leap.Unity {
14
15 public static class ArrayPool<T> {
16 private static Dictionary<int, Stack<T[]>> _bins;
17
18 static ArrayPool() {
19 _bins = new Dictionary<int, Stack<T[]>>();
20
21 _bins[0] = new Stack<T[]>();
22 for (int i = 0; i < 32; i++) {
23 _bins[1 << i] = new Stack<T[]>();
24 }
25 }
26
35 public static T[] Spawn(int minLength) {
36 int count = Mathf.NextPowerOfTwo(minLength);
37 var bin = _bins[count];
38
39 if (bin.Count > 0) {
40 return bin.Pop();
41 } else {
42 return new T[count];
43 }
44 }
45
50 public static void Recycle(T[] array) {
51 Array.Clear(array, 0, array.Length);
52 int binKey = Mathf.NextPowerOfTwo(array.Length + 1) / 2;
53 _bins[binKey].Push(array);
54 }
55 }
56}