The GNU C Library - Efficiency and Malloc

Node: Efficiency and Malloc Next: Aligned Memory Blocks Prev: Allocating Cleared Space Up: Unconstrained Allocation

Efficiency Considerations for malloc

To make the best use of malloc , it helps to know that the GNU version of malloc always dispenses small amounts of memory in blocks whose sizes are powers of two. It keeps separate pools for each power of two. This holds for sizes up to a page size. Therefore, if you are free to choose the size of a small block in order to make malloc more efficient, make it a power of two.

Once a page is split up for a particular block size, it can't be reused for another size unless all the blocks in it are freed. In many programs, this is unlikely to happen. Thus, you can sometimes make a program use memory more efficiently by using blocks of the same size for many different purposes.

When you ask for memory blocks of a page or larger, malloc uses a different strategy; it rounds the size up to a multiple of a page, and it can coalesce and split blocks as needed.

The reason for the two strategies is that it is important to allocate and free small blocks as fast as possible, but speed is less important for a large block since the program normally spends a fair amount of time using it. Also, large blocks are normally fewer in number. Therefore, for large blocks, it makes sense to use a method which takes more time to minimize the wasted space.


Next: Aligned Memory Blocks Up: Unconstrained Allocation