Memory Management

Allocating and deallocating heap memory on the fly is expensive. From a performance perspective, it is cheaper to work with memory that does not necessitate explicit management. An object defined as a local variable resides on the stack. Stack memory occupied by this object is part of the stack memory set aside for the function in whose scope the object is defined. The alternative to a local object is using new() and delete() to acquire and release heap memory:

void f()
{
    X *xPtr = new X;
    ...
    delete xPtr;
}

A better performance choice would be to define a local object of type X:

void f()
{
    X x;
    ...
}  // no need to delete x.

In the latter implementation, object x is on the stack. There's no need to allocate it up front, or ...

Get Efficient C++ Performance Programming Techniques now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.