Why not allocate and deallocate memory frequently in C++ games? -
i'm recent convert c++ game programming - have lot of experience dealing memory management , garbage collection woes in c#, not c++.
i've heard vague advice in past avoid allocations , deallocations during gameplay (i.e. new
, delete
) , pre-allocate might need front. that's lot more tedious , architecturally complex allocating , freeing game objects needed while game's running (enemies, particles, etc.).
i think advice read referring resource-constrained platforms - i'm aiming develop pc, , imagine game state data changing on order of few megabytes @ most. rest textures, sound assets, etc. i'll preloading.
so question is: in world of pcs gigabytes of memory, worth headache set elaborate memory pooling, pre-allocation, , forth game state data? or unquestioned "best practice" tradition evolved when maxing out limited platforms, repeated gospel?
if 2 mb of game data gets fragmented , spread on 4mb, can't imagine mattering in slightest on pc made after 1990 - curious know if i'm missing :).
the main reasons avoid calling new
unless necessary in game environment
- dynamic allocation of memory surprisingly expensive.
- cache misses detrimental performance.
dynamic allocation
at work, develop game-like product (virtual surgery) , of our memory pre-allocated , handled via factories or memory pools. done because, dynamically allocating memory takes long time. system has deal memory requests of many different sizes @ , times. means there's lot of work going processes such minimizing fragmentation. if ask system memory, you'll have wait these things. if pre-allocate memory, can use factories or other block-size-specific memory managers alleviate these concerns.
i can tell experience simple mistake allocating reasonably large std::vector
scratch every frame, instead of reusing pre-allocated memory, can drag frame rate down gutter.
cache misses
another related issue cache coherence. cache misses, force os bring new page cache, expensive. if happens often, you'll have unplayable game. if, however, pre-allocate large chunks of memory, can go long way towards improving cache locality, makes cache misses few , far between.
moral of story
so, in short: if don't manage own pre-allocated memory, can expect lot of computational time lost waiting system allocate memory or handle cache misses.
Comments
Post a Comment