Eric Sosman
4/21/2011 2:41:00 AM
On 4/20/2011 3:21 PM, Steve Keller wrote:
> I have lots and lots of malloc() and free() calls for memory of
> varying size, ranging from 100 to 500 bytes. How efficient will
> malloc() be concerning execution time and fragmentation if I pass the
> required sizes directly to malloc() as opposed to rounding them up.
For execution time, you'll need to measure. Be aware that you
will probably get different results on different platforms.
For fragmentation, rounding up might perhaps reduce external
fragmentation (unusable space between allocated blocks), but it is
absolutely 100% guaranteed to increase internal fragmentation (space
allocated within blocks but not used).
> Will I help malloc() to improve performance if I call
> malloc(ROUND(size)) instead with e.g.
>
> // Round up to multiple of 64
> #define ROUND(n) (((n) + 63)& ~63)
>
> or even rounding up to the next power of two?
Measure. It's worth noting, though, that many allocators add a
few bytes of overhead to each block requested, that some allocators
already work in power-of-two sizes, and therefore if you round your
request up to a power of two you will consume twice as much memory as
if you hadn't. For example, if you need 33KB and round it up to 64KB,
and the allocator tacks on 8 bytes of overhead for a total of 64KB+8,
then rounds the total up to 128KB. Had you simply asked for 33KB to
start with, you'd have used only half as much address space.
Advice: (1) As a default policy, just ask for what you need and
leave it to the allocator to figure out how best to satisfy the need.
(2) If you determine BY MEASUREMENT that the allocator can't handle
your request stream satisfactorily, then and only then should you try
to outsmart it, and you must MEASURE to ensure that your attempts to
outsmart don't in fact outstupid.
--
Eric Sosman
esosman@ieee-dot-org.invalid