Reputation: 67
I am implementing a memory pool in C++, with the following constraints:
Allocation and deallocation would happen frequently during the runtime of a real-time program, so needs to happen as fast as possible.
I have so far implemented this memory pool using two linked lists as stubs, one for the free and one for the allocated elements. This works, but is of course terribly slow, since every time an element is either freed or allocated, the element needs to be removed from one list and added to the other, which is linear. I would like this to be faster.
What data structures could I use to make (de)allocation as efficient as possible? I was thinking about using a red-black tree (or similar balancing BST) to store the allocated elements, and a priority queue for the free elements. This would make allocation and deallocation both O(log n).
Any advice on how I could improve this design? Other data structures I could use? Is it even possible to make a memory pool (with the above constraints) with constant time operations?
Edit: I should probably clarify that these data structures are meant only for storing and accessing the memory addresses, the memory blocks themselves are already allocated and contiguous.
Upvotes: 1
Views: 1787
Reputation: 16243
Since we're dealing with a memory pool with fixed size memory blocks, constant time operations can be achieved as follows eg. :
block_address = base_address + index * block_size
, and vice versa).prev
and next
pointers.How does this fit the requirements :
Upvotes: 1