Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting vs allocation/deallocation - efficiency

I am writing a C++ application which will require a block of memory (about 1000 bytes) as a temporary buffer for some text processing. The operation may be repeated up to 10,000 times a second.

Could anybody confirm that it would be more expensive to allocate the memory each time I need the buffer (i.e. new with a smart pointer, memory is deallocated when out of scope), than to have a fixed buffer and clear it (write every byte of it with a zero) every time the processing is complete?

It sounds like common sense for C++ but I just cannot find anything on the internet which confirms it.

Is the situation different for computer languages with automatic garbage collection facilities (e.g. Java, .net)?

like image 293
Andy Avatar asked Jun 02 '09 13:06

Andy


1 Answers

It's probably more expensive to allocate and free the memory each time you need it, but the bigger question is: does it matter? Write it the easiest way you know how that works correctly and doesn't leak/corrupt memory. Only then if your performance isn't good enough, profile the code to see where you can improve it.

like image 161
Michael Kristofik Avatar answered Oct 25 '22 17:10

Michael Kristofik