Use ObjectPool in ConcurrentStack
authorJérémie Laval <jeremie.laval@gmail.com>
Mon, 14 Feb 2011 18:10:42 +0000 (18:10 +0000)
committerJérémie Laval <jeremie.laval@gmail.com>
Mon, 14 Feb 2011 18:12:41 +0000 (18:12 +0000)
mcs/class/corlib/System.Collections.Concurrent/ConcurrentStack.cs

index 2e059b684d2efe64b404616f58364b3ee99f05b4..abc9e5822f1d461e2deccdd61782bb8c5f0add9f 100644 (file)
@@ -47,6 +47,21 @@ namespace System.Collections.Concurrent
                Node head = null;
                
                int count;
+
+               class NodeObjectPool : ObjectPool<Node> {
+                       protected override Node Creator ()
+                       {
+                               return new Node ();
+                       }
+               }
+               static readonly NodeObjectPool pool = new NodeObjectPool ();
+
+               static Node ZeroOut (Node node)
+               {
+                       node.Value = default(T);
+                       node.Next = null;
+                       return node;
+               }
                
                public ConcurrentStack ()
                {
@@ -66,7 +81,7 @@ namespace System.Collections.Concurrent
                
                public void Push (T item)
                {
-                       Node temp = new Node ();
+                       Node temp = pool.Take ();
                        temp.Value = item;
                        do {
                          temp.Next = head;
@@ -86,7 +101,7 @@ namespace System.Collections.Concurrent
                        Node first = null;
                        
                        for (int i = startIndex; i < count; i++) {
-                               Node temp = new Node ();
+                               Node temp = pool.Take ();
                                temp.Value = items[i];
                                temp.Next = insert;
                                insert = temp;
@@ -117,6 +132,8 @@ namespace System.Collections.Concurrent
                        Interlocked.Decrement (ref count);
                        
                        result = temp.Value;
+                       pool.Release (ZeroOut (temp));
+
                        return true;
                }
 
@@ -145,7 +162,9 @@ namespace System.Collections.Concurrent
                        int i;
                        for (i = startIndex; i < count && temp != null; i++) {
                                items[i] = temp.Value;
+                               end = temp;
                                temp = temp.Next;
+                               pool.Release (ZeroOut (end));
                        }
                        
                        return i - 1;