Which is preferable way to allocate memory for a function that is frequently allocating and freeing memory ? Assume this function is getting called around 500 to 1000 times a second on a 1GHz Processor.
(Please ignore static and global variables/allocation. I am interested only this specific case:)
void Test()
{
ptr=malloc(512) // 512 bytes
...
free(ptr)
}
OR
void Test()
{
struct MyStruct localvar; // 512 byte sized structure
...
}
stack allocation of local variables is faster than heap allocation with
malloc. However, the total stack space is limited (e.g. to several megabytes). So you should limit yourself to “small” data on the local stack. (and 512 bytes is small by today’s standard, but 256Kb would be too large for local stack allocation).If your function is very deeply recursive, then perhaps even 512 bytes could be too big, because you’ll need that for each recursive call frame.
But calling
malloca few thousands time per second should be painless (IMHO a typical small-sizedmalloctakes a few dozens of microseconds).For your curiosity, and outside of the C world, you might be interested by old A.Appel’s paper garbage collection can be faster than stack allocation (but perhaps cache performance considerations could weaken this claim today).