Constructors and Destructors

Always take care of the overhead resulted from invoking constructors and destructors of an object.

If the construct (or destructor) is called frequently, it’s recommended to inline it.

This is not to say that inheritance is fundamentally a performance obstacle. We must make a distinction between the overall computational cost, required cost, and computational penalty. The overall computational cost is the set of all instructions executed in a computation. The required cost is that subset of instructions whose results are necessary. This part of the computation is mandatory; computational penalty is the rest. This is the part of the computation that could have been eliminated by an alternative design or implementation.

Initializing data members as pointer to objects let you initialize them whenever you want. Further, it lets you partially instantiate them. Further, allocating objects at run time consumes performance where the standalone object initialization allocates its memory (on the stack) at compilation time. It’s a trade-off, you must pick what is more suitable for you.

The habit of automatically defining all objects up front could be wasteful—you may construct objects that you end up not using. So, initialize code where you’ll sure need it. As an example observes packet variable in the 2 code fragments below:

After optimization:

This is called, lazy construction.

When initializing a data member in a class, use the initialization list rather than assigning a value to the data member in the constructor body. In strings, this reclaimed about 50 ms.

Key Points:

  • Constructors and destructors may be as efficient as hand-crafted C code. In practice, however, they often contain overhead in the form of superfluous computations.
  • The construction (destruction) of an object triggers recursive construction (destruction) of parent and member objects. Watch out for the combinatorial explosion of objects in complex hierarchies. They make construction and destruction more expensive.
  • Make sure that your code actually uses all the objects that it creates and the computations that they perform.
  • Don’t create an object unless you are going to use it.

Compilers must initialize contained member objects prior to entering the constructor body. You ought to use the initialization phase to complete the member object creation. This will save the overhead of calling the assignment operator later in the constructor body. In some cases, it will also avoid the generation of temporary objects.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s