Why does our code run faster if we use initialization lists rather than assignment in class constructor?

(Last Updated On: January 1, 2015)

Hint to understand the question: Notice the below class A for using initializer list and assignment operator in C++.

Class constructor using initialization list:

Class constructor using assignment operator:

Answer:

Using initialization list in constructor is the one step process i.e. it initializes objects at the moment it’s declared. It calls copy constructor.

Whereas using assignment is the two-step process i.e. define the object and then assign it. Defining objects calls default constructor and then assignment calls assignment operator. Hence, expensive operations.

That’s the reason, using initialization list has better performance than using assignment operator in constructor.

Notes:

  1. We don’t see any performance difference in both the cases, in case of in-built objects like int, float or small objects. That’s the reason in IT industries you might have seen using assignment operator at the maximum places in the project. But, if the objects are very complex then definitely we’ll notice the performance difference.
  2. An initializer list is the preferred way to initialize the members in a class constructor.
  3. Initialization list is the only possible way to initialize reference members and constant members of a class e.g.