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?