6 апр. 2010 г.

Фрагментация памяти.

Небольшя заметка по поводу фрагментации памяти в приложениях. В частности, можно отнести к теме C++. Во многих других языках есть автоматические сборщики мусора, которые в той или иной степени эту проблему решают. Заметка некоего Дэнни Калева (Danny Kalev) с мертвой страницы www.devx.com:


Preventing Memory Fragmentation


Applications that are free from memory leaks but perform dynamic memory allocation and deallocation frequently tend to show gradual performance degradation if they are kept running for long periods. Finally, they crash. Why is this? Recurrent allocation and deallocation of dynamic memory causes the heap to become fragmented, especially if the application allocates small memory chunks (int, an 8 byte object etc.). A fragmented heap can have many free blocks, but these blocks are small and non-contiguous. To demonstrate this, look at the following scheme that represents the system's heap. Zeros indicate free memory blocks and ones indicate memory blocks that are in use:


100101010000101010110

The above heap is highly fragmented. Allocating a memory block that contains 5 units (i.e., 5 zeros) will fail, although the systems has 12 free units in total. This is because the free memory isn't contiguous. On the other hand, the following heap has less free memory but it's not fragmented:


1111111111000000

What can you do to avoid heap fragmentation? First of all, use dynamic memory as little as possible. In most cases, you can use static or automatic storage instead of allocating objects dynamically. Secondly, try to allocate large chunks rather than small ones. For example, instead of allocating a single object, allocate an array of objects at once, and use these objects when they are needed. If all these tips don't solve the fragmentation problem, you should consider building a custom memory pool.



В двух словах. При выделении большого числа блоков памяти в куче накапливаются неиспользуемые несмежные области, которые не используются. Со временем эти области заполняют всё выделенную приложению кучу и приложение падает. Основные тезисы:
1. Старайтесь не выделять много маленьких блоков, а выделить один большой.
2. Старайтесь использовать статические или автоматические хранилища.
3. Пишите собственный менеджер памяти.

Можно добавить совет повторно использовать выделенную память.

Комментариев нет:

Отправить комментарий