Tag Archives: performance

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).