On Aug 21, 1:49 am, "Scott McPhillips [MVP]" <org-dot-mvps-at-
scottmcpwrote:
Dynamic allocation is the ONLY solution to allocating memory at run time
(unless you use a language that provides garbage collection).
Getting there. I would argue that dynamic allocation IS - by the very
meaning of the word dynamic - allocation at run-time. It's not just
the only solution, it is indivisibly the thing itself. "garbage
collection" only refers to one aspect of the myriad design and
implementation choices for algorithms offering dynamic memory
management.
If you have
problems with fragmentation then the only thing you can do is smarter
dynamic allocation, which requires knowledge of the allocation requirements
of your application.
Precisely.
Mayank: what's good depends a lot on the patterns of memory usage.
There are a couple distinct aspects.
Firstly: there's how often you need to do allocations. For example,
if you are having trouble inserting millions of elements in a
container, then see if there are functions to preallocate the required
space rather than grow during insertions, or at least to resize more
aggressively (e.g. resize arrays or hash tables by x4 instead of x2
each time more space is needed). How much can be done depends on the
container: for example, linked lists aren't likely to allow any kind
of pre-allocation.
Secondly: you can decrease the time needed for the allocations you
really can't avoid. To do this, follow suggestions elsewhere in this
thread, and use a custom allocator from boost.
So, to work out which direction to head down, you should profile your
application and work out which containers are causing you trouble,
during what kind of operations (insert, lookup, erase).
Taking a step back, in your original post:
Its said that one should avoid dynamic allocation of memory, as it de-
fragment the memory into small chunks and allocation of memory is a
costly process in terms of efficiency. So what is the best solution to
handle to situation in which we need to allocate memory at run time.
"It's said" suggests even looking at memory allocation may be a path
you've started on with no clear evidence from actual profiling. Did
someone at work tell you "this things slow, think it's the memory
allocation", and ask you to fix it? Don't believe them unless you see
hard evidence in the form of profiling results: you'll waste a lot of
time.
Cheers,
Tony