Implementing objects with short life time but that have to be created frequently

Started by
12 comments, last by SiCrane 11 years, 5 months ago
An idea:
You allocate the array
Bullets **bullets= new Bullets*[200]

Then you make 2 lists:
list<Bullets*> dead_bullets, alive_bullets

....first all bullets(pointers) are in the dead_bullets and when a bullet is needed you put it into the alive_bullets and remove it from dead_bullets.

edit:
of course you fill the array first:)
for(...)
bullets= new Bullet()
Advertisement

So for a list, to add a bullet, it first uses new to allocate a space, and then constructs the bullet object.
But for a vector, it constructs the bullet object right away because memory is already allocated.

Am I right?

Basically, yes. However, if vector runs out of free allocated memory, it'll have to get a new chunk of memory, and move every element to the new chunk of memory.
Vector holds all its elements in one continuous block of memory (faster traversals, slower insertion), list holds each element in their own block of memory (longer traversals, faster insertion).

If you know in advance how many elements you'll have the vector hold, you can call vector.reserve() and then push_back() and pop_back() without fear of reallocation causing an unexpected slowdown. By "slower" and "faster" we're talking about time periods that all less than 1/100,000th of a second - unless you are really hitting everything tens of thousands of times a frame, these kinds of "which is faster in what situation" issues can mostly be ignored until you find yourself actually needing the extra speed.
If you have other objects with a short live time (per frame, per level, ...) you could also take a look at region based memory management.
I would guess for bullets it's not that optimal, but for other objects that have a predictable life time it's a simple way to prevent memory leaks.

The standard C++ containers use a pooled-allocation strategy.

Not necessarily. The standard allows pooled allocation, but doesn't require it.
The don't use [font=courier new,courier,monospace]new[/font] and [font=courier new,courier,monospace]delete[/font] for memory allocation, they use a [font=courier new,courier,monospace]std::allocator[/font] object (which may or may not use [font=courier new,courier,monospace]new[/font] and [font=courier new,courier,monospace]delete[/font]) which will actually keep the memory hanging around after a contained object is freed.[/quote]
Actually std::allocator itself is required to use new to allocate memory, though how often it is used (e.g. if it is called with every call to allocate()) is left unspecified. Other allocators may or may not use new.

This topic is closed to new replies.

Advertisement