Recycling .net objects to improve performances

C# .Net allocation and freeing system is quite efficient but when you need to create a huge number of objects, it’s just not fast enough. So what you can do is try to recycle each object to avoid to recreate them. You will then just need to set their property.

In my tests, this class reduced the allocation time from 12 to 15 times:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public sealed class Heap<T> where T:class, new() {
	private readonly Stack<T> _stack = new Stack<T>();
 
	private int _count;
 
	public T Allocate() {
                if ( _count == 0 ) {
                   return new T();
                } else {
                  --_count;
                  return _stack.Pop();
                }
	}
 
	public void Free( T obj ) {
		++_count;
		_stack.Push( obj );
	}
}

You might think that this process is really painful as you have to manually free every single objects you use. But in fact you just have to recycle most of the objects. If you forget some, that’s not really important (they will just get garbage collected).

2 thoughts on “Recycling .net objects to improve performances”

  1. I have had an idea of an algorithm to recycle Reference Type objects, then I made research about it and found this article.

    The algorithm I thought of is pretty much like yours, the only differences being that it is a little more readable for a newbie like me and it uses a List instead of a Stack.

    Is there any difference if I use a List or a Queue as a “recycle bin” instead of a Stack?

    1. I think the code I gave was wrong, it was never reducing the number of count. I “fixed” it but didn’t test it yet.

      List and Stack should have similar performances because they should both internally contain an darray. You should definitely test this code with List. I only chose a Stack because I find it more explicit.

Leave a Reply

Your email address will not be published. Required fields are marked *