knowwis
knowwis

Reputation: 97

What is the best way to allocate on heap: small pieces or big piece

For example I have a code

for (int i = 0; i < 1000; ++i)
{
    Object obj = new Object();
    /* Manipulation */
}

What is the best way to do this:

I need this objects outside of loop.

I am thinking about problems, when heap cannot find chunk big enough as size I requested.

Upvotes: 0

Views: 204

Answers (2)

Purag
Purag

Reputation: 17061

As it stands, your code will not be efficient at all, no matter how you allocate. You're dynamically allocating thousands of bytes and never deallocating them; it doesn't matter if you do it in the loop or outside. On each iteration, you will take up more unused bytes in the heap.

Now, if you use stack allocation, then your object will be destructed implicitly after each loop iteration, and you don't need to worry about deallocating it manually.

But here's the thing—you don't need to allocate sizeof(Object) * 1000 bytes, because either way the scope of your object is the loop. If you don't plan on accessing the object outside of the loop (and I don't imagine you would, since you're making thousands of them and the only one you'd retain access to is the last one), then you only need room for one object.

The C++ compiler actually does this automatically. When your function gets called, it will allocate sizeof(Object) bytes for the local variable obj, and on each iteration, you're just overwriting those same bytes.

So in short, the only thing you need to worry about is deallocating after each iteration, which can be achieved more simply by allocating on the stack as opposed to the heap.

There is slight overhead if you are to use dynamic allocation along with a delete at the end of each iteration. You will have sizeof(Object) bytes in the heap and also 4 bytes on the stack for the pointer to the heap, which is obj. 4 bytes is certainly negligible in most cases, but worth noting.

Of course, allocating those thousands of bytes for the Objects is much more memory-intensive than overwriting the same few bytes, especially if you only intend for the lifetime to be a single iteration.

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106126

One larger allocation will save a little time during allocation and deallocation, assuming you want the lifetimes of the objects to be the same. There could be reasons not to, but in general I'd recommend using std::vector<Object> objects(1000); before the loop, then modifying objects[i] inside the loop, or even looping...

for (Object& object : objects)
    ...

...if you don't need i for anything else.

Upvotes: 1

Related Questions