O'Reilly logo

Efficient C++ Performance Programming Techniques by David Mayhew, Dov Bulka

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required