Hi, I read that for user-defined types, postponing the defintion of a variable until a suitable initializer is available can lead to better performance. why?
views:
111answers:
4Because it means a constructor other than the default constructor is called.
X x; // Calls X()
x.Set(42);
X x(42); // Calls X(int)
You avoid running an unnecessary constructor followed by an Init call when the proper initialization data is available. And, if the code path never reaches the initialization branch you can avoid the constructor and destructor all together, plus an exception handling state setup for the unwinding.
Consider a string class. If we say:
string s;
....
s = "foobar";
then we have to do some work in the construction of s, and then more or less repeat the same work in the assignment. If we do:
string s( "foobar" );
we do the work once only.
Having said that, when learning C++ you should never concern yourself with issues of performance - think only about writing clear and understandable code. And in this case, initialisation with a value also wins out - code is clearer if variables are always initialised.
And BTW, the language is called C++ - cpp is the C preprocessor.
For user-defined types in particular, the constructor and setting method could me arbitrarily complex and time-consuming. Taking Steven's example:
X x; // Calls X()
x.Set(42);
X x(42); // Calls X(int)
... the implementation of X::X() and X::Set() might both be very time-consuming, and that's why you read that the latter can have better performance.