Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do C++ standard library containers use memory pools, if apparently the malloc/free pair does the same job?

I've read that repetitive calls to malloc/free can be expensive and for this reason C++ standard library containers use memory pools rather than calling free in their destructors. Also, I've read, this means that the performance of C++ standard library containers can be higher than manually allocating and deallocating all necessary C-style arrays.

However, I'm confused about this, since now I'm reading in the C FAQ: ( http://c-faq.com/malloc/freetoOS.html )

Most implementations of malloc/free do not return freed memory to the operating system, but merely make it available for future malloc calls within the same program.

This means that essentially the malloc/free functions try to do the very same job as the C++ standard library containers: They try to optimize repetitive claiming/reclaiming memory by keeping memory in a pool and then giving the program pieces of this pool on request. While I can see the benefits of such an optimization if performed once, my intuition tells me that if we start doing this on a few different layers of abstraction simultaneously the performance is likely to actually decrease - as we will be duplicating the same work.

What am I misunderstanding here?


1 Answers

Some implementations of the standard library use memory pools.

In general, when you know the memory needs of a particular container, you might be able to do a better job of managing its memory than a general-purpose memory manager that doesn't know your container's specific needs.

For example, if you're using std::list<int> every node in the list is the same size, and having the container maintain a list of unused nodes (just two pointer assignments to add or remove a node to/from the free list) may be faster than releasing unused nodes back to the more general but more complex general-purpose memory manager used by new/delete (malloc/free).

like image 191
Pete Becker Avatar answered Dec 05 '25 11:12

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!