Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing memory fragmentation with the new - delete trick

I remember reading in a book on programming for computer games, sorry can't remember title. That an easy way to improve performance is do something like this near the start:

int main()
{
 {
   char dummy* = new char[10000000];  // 10Mbytes ish
   delete[] dummy;
 }
 ...
}

The idea is that the expensive part of dynamic memory allocation is the request to get memory from the OS, which doesn't normally get returned until the end of the program. Has anybody used this and seen performance improvements ?

like image 284
Chris Huang-Leaver Avatar asked Jan 20 '23 11:01

Chris Huang-Leaver


2 Answers

Whether this works or not depends on the OS in question. A lot of modern OSes use mmap under the hood for large memory allocation and bypass the process's heap altogether. This means the allocation will be made directly from the OS and then returned directly to the OS when freed.

A much better strategy is to generally do your memory allocation at the start and reuse space allocated as much as possible before returning the memory to the heap. This is the logic behind STL allocators.

like image 188
doron Avatar answered Feb 19 '23 11:02

doron


That doesn't make sense. You allocate a huge block, then free it and the heap takes ownership of the memory occupied by the block and can legally fragment it while it is used later.

like image 20
sharptooth Avatar answered Feb 19 '23 11:02

sharptooth