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 malloc
a few thousands time per second should be painless (IMHO a typical small-sized malloc
takes 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).
Local variables are allocated essentially "for free", so there is no contest here if we are only interested in performance.
However:
- Which is preferable way to allocate memory....
- Which allocation is faster ?
Do you want the faster way,or the preferable way?
Anyway, in the case you mentioned, I think the second option:
struct MyStruct localvar;
is more efficient, since the memory allocation is done by the Stack. Which is a lot more efficient that using dynamic memory allocation functions like malloc
.
Also, if you are doing this for performance & optimizing...
On my PC, using malloc
to allocate strings instead of declaring a char array from the stack gives me a lag of ~ 73 nanoseconds per string.
if you copied 50 strings in your program: 4757142 / 50 = 95142 (and a bit) runs of your program
If I run your program 50 times a day: 95142 / 50 = 1902 (and a bit) days
1902 days = 5 1/5 years
So if you run your program every day for 5 years and 2 months, you'll save the time to blink your eye an extra time. Wow, how rewarding...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With