C++ Constructors vs Initialization Lists speed comparison

Sebi picture Sebi · Nov 3, 2012 · Viewed 19.5k times · Source

Are there any differences in execution time between constructors and initialization lists?(or is it just a matter of coding preference). I have a set of objects that needs to be created frequently and would like to know if there is any performance gain by using initialization lists instead of constructors.

If I were to create a million instances of class A and another million of class B which choice would be better(the objects represent packets generated within a network hence these numbers).

 class A {
   private:
     int a, b;

   public:
     A(int a_var, int b_var):a(a_var), b(b_var) {}; 
 };

 class B {
   private:
     int a, b;

   public:
     B(int a_var, int b_var) {
        a = a_var;
        b = b_var;
     }
};

If any of the constructors is faster than the other for primitive types(as in the example) will it be faster if a and b were to be replaced by types?

Type example:

 class AType {
   private:
     string a, b;

   public:
     AType(string a_var, string b_var):a(a_var), b(b_var) {}; 
};

Answer

PiotrNycz picture PiotrNycz · Nov 3, 2012

The difference is for types with no trivial default constructor, which is called for you by compiler in your class B. Your class B is equivalent to:

 class B {
   private:
     SleepyInt a, b;

   public:
     // takes at least 20s
     B(int a_var, int b_var) : a(), b()
     //                      ^^^^^^^^^^ 
     {
        a = a_var;
        b = b_var;
     }
  };

If you do not place member variable or base class constructor in initialization list - ithe default constructor is called for them. int is basic type - its default constructor costs nothing - so no difference in your example, but for more complex types constructor+assignment might cost more than just constructing.

Some funny example, just to illustrate the difference:

class SleepyInt {
public:
  SleepyInt () { 
    std::this_thread::sleep_for(std::chrono::milliseconds( 10000 ));  
  }
  SleepyInt (int i) {}
  SleepyInt & operator = (int i) { return *this; }
};

class A {
   private:
     SleepyInt a, b;

   public:
     A(int a_var, int b_var):a(a_var), b(b_var) {}; 
 };

 class B {
   private:
     SleepyInt a, b;

   public:
     // takes at least 20s
     B(int a_var, int b_var) {
        a = a_var;
        b = b_var;
     }
};