Florent Clairambault

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: 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 == ) { return new T(); } else { --_count; return _stack.