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) {};
};
The difference is for types with no trivial default constructor, which is called for you by compiler in your class
B. Your classBis equivalent to:If you do not place member variable or base class constructor in initialization list – ithe default constructor is called for them.
intis 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: