You could also consider using Boehm conservative garbage collector. Basically, you replace every malloc
in your source code with GC_malloc
(etc...), and you don't bother calling free
. Boehm's GC don't allocate memory more quickly than malloc (it is about the same, or can be 30% slower), but it has the advantage to deal with useless memory zones automatically, which might improve your program (and certainly eases coding, since you don't care any more about free). And Boehm's GC can also be used as a C++ allocator.
If you really think that malloc
is too slow (but you should benchmark; most malloc
-s take less than microsecond), and if you fully understand the allocating behavior of your program, you might replace some malloc-s with your special allocator (which could, for instance, get memory from the kernel in big chunks using mmap
and manage memory by yourself). But I believe doing that is a pain. In C++ you have the allocator concept and std::allocator_traits
, with most standard containers templates accepting such an allocator (see also std::allocator
), e.g. the optional second template argument to std::vector
, etc...
As others suggested, if you believe malloc
is a bottleneck, you could allocate data in chunks (or using arenas), or just in an array.
Sometimes, implementing a specialized copying garbage collector (for some of your data) could help. Consider perhaps MPS.
But don't forget that premature optimization is evil and please benchmark & profile your application to understand exactly where time is lost.
malloc
in C++? – Dimpledimwitnew
rely onmalloc
to get memory anyway... – Centric