Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PushGP/HeuristicLab.PushGP/TestPooling/Pool/ManagedPool.cs @ 14791

Last change on this file since 14791 was 14745, checked in by pkimmesw, 8 years ago

#2665 Merged ExecExpandExpression and PushProgram due to performance reasons, Tested managed object pooling

File size: 1.6 KB
Line 
1using System.Collections.Generic;
2
3namespace TestPooling.Pool {
4  using System;
5  using System.Collections.Concurrent;
6  using System.Linq;
7
8  public class ManagedPool<T> : IDisposable where T : class {
9
10    private static readonly ConcurrentStack<LinkedList<T>> Pool = new ConcurrentStack<LinkedList<T>>();
11    private readonly Func<T> Factory;
12    public readonly int PartitionSize;
13
14    private readonly IList<LinkedList<T>> partitions = new List<LinkedList<T>>();
15    private LinkedList<T> currentPartition;
16    private LinkedListNode<T> currentNode;
17
18    private int entryIndex = 0;
19
20    public static int InstanceCount { get { return Pool.Sum(p => p.Count); } }
21
22    public ManagedPool(int partitionSize, Func<T> factory) {
23      PartitionSize = partitionSize;
24      Factory = factory;
25    }
26
27    public T Get() {
28      if (currentPartition == null || entryIndex == PartitionSize) {
29        currentPartition = GetPartition();
30        currentNode = currentPartition.First;
31        entryIndex = 0;
32
33        partitions.Add(currentPartition);
34      }
35
36      T entry;
37      if (currentNode == null) {
38        entry = Factory();
39        currentPartition.AddLast(entry);
40      } else {
41        entry = currentNode.Value;
42        currentNode = currentNode.Next;
43      }
44
45      entryIndex++;
46
47      return entry;
48    }
49
50    private LinkedList<T> GetPartition() {
51      LinkedList<T> partition;
52
53      return Pool.TryPop(out partition) ? partition : new LinkedList<T>();
54    }
55
56    public void Dispose() {
57      Pool.PushRange(partitions.ToArray());
58    }
59  }
60}
Note: See TracBrowser for help on using the repository browser.