开发者

Preventing memory fragmentation with the new - delete trick

开发者 https://www.devze.com 2023-02-10 21:13 出处:网络
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:

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 ?


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.


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.


That doesn't necessarily improve performance, as the current Standard says nothing about how the memory is dynamically allocated, deallocated and then reallocated. However, an implementation can make use of the same memory region in the rest of the program whenever it needs to allocate memory . It's more like memory pooling.

Anything could be possible. It entirely depends on implementation. Also it may even choose to remove the code altogether, as it does nothing.


Depending on your environment, there may be loader flags that let you specify an initial heap size. This memory will be allocated when your program is loaded into memory, so it becomes part of the start-up time. This should give the same results, with the benefit that the compiler won't optimize it away.

0

精彩评论

暂无评论...
验证码 换一张
取 消