Advantages of Using Multiple Heaps

Using a single run-time heap is adequate for most programs. However, using multiple heaps can be more efficient and can help improve performance and reduce wasted memory for a number of reasons:

Avoid memory blocks scattered over different pages of memory

When you allocate from a single heap, you may end up with memory blocks on different pages of memory. For example, you might have a linked list that allocates memory each time you add a node to the list. If you allocate memory for other data in between adding nodes, the memory blocks for the nodes could end up on many different pages. To access the data in the list, the system may have to swap many pages, which can significantly slow your program.

Designate heaps for specific purposes

With multiple heaps, you can specify which heap you allocate from. For example, you might create a heap specifically for the linked list. The list's memory blocks and the data they contain would remain close together on fewer pages, reducing the amount of swapping required.

Improve performance in multithread applications

In multithread applications, only one thread can access the heap at a time to ensure memory is safely allocated and freed. For example, if thread 1 is allocating memory, and thread 2 has a call to free, thread 2 must wait until thread 1 has finished its allocation before it can access the heap. Again, this can slow down performance, especially if your program performs many heap operations.

If you create a separate heap for each thread, you can allocate from them concurrently, eliminating both the waiting period and the overhead required to serialize access to the heap.

Free related blocks of memory with a single call

With a single heap, you must explicitly free each block that you allocate. If you have a linked list that allocates memory for each node, you have to traverse the entire list and free each block individually, which can take some time.

If you create a separate heap for that linked list, you can destroy it with a single call and free all the memory at once.

Limit the effect of heap damage and help with its diagnosis.

When you have only one heap, all components share it (including the IBM C and C++ Compilers run-time library, vendor libraries, and your own code). If one component corrupts the heap, another component might fail. You may have trouble finding the cause of the problem and where the heap was damaged.

With multiple heaps, you can create a separate heap for each component, so if one damages the heap (for example, by using a freed pointer), the others can continue unaffected. You will also know where to look for the problem.



Manage Memory with Multiple Heaps
Heap-Specific Functions