Search code examples
c#memoryheap-memoryallocation

Custom memory allocators or memory pools


I am using a third-party networking library and in order to send a network message I need to create a new instance of the NetworkMessage class. This is inefficient because the application needs to run very fast and there are a lot of messages sent around, so I am looking for a way to avoid dynamic memory allocation for every message.

If the NetworkMessage was a struct then we wouldn't have a problem. Also I cannot store a number of precreated NetworkMessage instances because the message arguments can only be passed in the constructor and they cannot be altered later on. I cannot change anything in the NetworkMessage class as it is third party.

Is there a way to create a memory pool in C# and then use something similar to the placement new operator from C++ to create objects from that pool? ( I know that there is no placement new operator in C# ). I'm looking for a way to initialize a block of memory and then use chunks of that memory to create instances of the NetworkMessage class from that.


Solution

  • Before we go on, one remark: memory allocation is super-efficient in .NET. It is not an expensive operation like it was in COM.

    That being said, I see two solutions:

    One thing you can do is to simply create a pool of NetworkMessage instances yourself. You can then take them and release them from the pool using a simple manager class.

    Another option is to use an inversion of control container such as Castle Windsor, Unity or NInject. Such containers handle dependency creation and object lifetime management for you.

    Good luck!