Hi all,
Many users claim that malloc() and free() provided by the language
library results in considerable
amount of overhead in terms of calling the same. Can we really
eliminate overhead by using
used defined functions/user defined memory manager. Is there any
significant advantage in providing user defined malloc() and free(). I
want to exclude realtime systems or embedded systems which are memory
constrained here.
I am talking about general purpose applications. With a user defined
memory manager can it handle
memory allocation and de-allocation in a much better way than what OS
would have done. Any inputs/comments
on the same are highly appreciated.
it actually really depends...
if one doesn't have a good grasp on what they are doing, then a custom
allocator is usually a good deal worse than the native malloc()/free()
WRT overhead and/or performance.
however, special purpose allocators can do well for certain tasks, such
as being faster, or being more compact for tiny objects, but usually
there are trade-offs.
the main reason, in my case, I do a custom allocator is mostly for:
1, I use GC (often both a friend and an enemy at times);
2, I use dynamic typing, and dynamic type-checking and malloc are not
friends;
3, my heap tends to often be dominated by small objects (and so certain
special-cases, such as "cons cells" have special handling, and certain
other special types are not even in addressable memory, as the pointer
itself encodes the value);
....
for example: cons cells are 8 bytes on x86 (they only ever hold 2
pointers), so it makes sense not to waste extra bytes on things like
having a header or padding the object to a multiple of 16 bytes.
also, they can easily end up (in certain types of app, such as those
making lots of use of list-processing) being the single most common
data-type on the heap.
a secondary common data-type is strings, which if one is using
interned/immutable strings, then having compact storage (such as
byte-aligned string tables) may make a good amount of sense (as strings
are also one of those things which can easily eat *lots* of memory,
hence my personal belief that UTF-16 is rarely a sensible option vs
UTF-8 or similar). granted, in other cases, it also makes sense to have
strings in a form where they may either be mutable or are subject to
being freed (it does not make sense to intern character buffers or large
one-off strings, for example...).
but, the custom MM/GC is mostly for GC and dynamic type-checking, rather
than to try to save bytes or be faster (although it may do this in
certain cases).
but, if I were just doing "generic" stuff, then malloc would probably be
fine, and simply trying to use a custom malloc as some perceived way to
make allocating/freeing structs or arrays faster (or save a few bytes)
is, IMO, a clear case of premature optimization...
or such...