forked from mirror/DotRecast
Use object pools instead of allocating new lists
This commit is contained in:
parent
3e754529e5
commit
c0b916a0d1
|
@ -0,0 +1,30 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DotRecast.Core.Buffers
|
||||
{
|
||||
// This implementation is thread unsafe
|
||||
public class RcObjectPool<T> where T : class
|
||||
{
|
||||
private readonly Queue<T> _items = new Queue<T>();
|
||||
private readonly Func<T> _createFunc;
|
||||
|
||||
public RcObjectPool(Func<T> createFunc)
|
||||
{
|
||||
_createFunc = createFunc;
|
||||
}
|
||||
|
||||
public T Get()
|
||||
{
|
||||
if (_items.TryDequeue(out var result))
|
||||
return result;
|
||||
|
||||
return _createFunc();
|
||||
}
|
||||
|
||||
public void Return(T obj)
|
||||
{
|
||||
_items.Enqueue(obj);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -21,6 +21,7 @@ freely, subject to the following restrictions:
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using DotRecast.Core.Buffers;
|
||||
|
||||
namespace DotRecast.Detour
|
||||
{
|
||||
|
@ -31,10 +32,12 @@ namespace DotRecast.Detour
|
|||
private int m_usedNodesCount;
|
||||
private List<DtNode[]> m_buckets;
|
||||
private readonly int m_initialBufferCapacityBase;
|
||||
private readonly RcObjectPool<List<DtNode>> m_listPool;
|
||||
|
||||
public DtNodePool(int initialBufferCapacityBase = 6) // initial size 64
|
||||
{
|
||||
m_map = new Dictionary<long, List<DtNode>>();
|
||||
m_listPool = new RcObjectPool<List<DtNode>>(() => new List<DtNode>());
|
||||
m_buckets = new List<DtNode[]>();
|
||||
m_initialBufferCapacityBase = initialBufferCapacityBase;
|
||||
}
|
||||
|
@ -78,6 +81,9 @@ namespace DotRecast.Detour
|
|||
|
||||
public void Clear()
|
||||
{
|
||||
foreach (var pair in m_map)
|
||||
m_listPool.Return(pair.Value);
|
||||
|
||||
m_map.Clear();
|
||||
m_usedNodesCount = 0;
|
||||
}
|
||||
|
@ -124,7 +130,8 @@ namespace DotRecast.Detour
|
|||
}
|
||||
else
|
||||
{
|
||||
nodes = new List<DtNode>();
|
||||
nodes = m_listPool.Get();
|
||||
nodes.Clear();
|
||||
m_map.Add(id, nodes);
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue