Interview Question
Not exactly sure of the performance impact by using member initalizer syntax for built in data types. But in the case of Objects(i mean composition.. i composed in the class), the first one is faster, since, in case 1, the object is created by invoking the copy constructor where as in case 2, the object i is initially created using the default constructor, then initialised using the copy constructor.
For built in data types, something like this
int i
i =j
int i=j
For objects.
Object i(j)
Object i;
i=j;
Dude, they generate _identical_ code on every C++ compiler I have access to. Don't make the mistake of confusing semantics with implementation.
found this in one website:
class Qux
{
public:
Qux() : _foo( "initialize foo to this!" ) { }
// This is nearly equivalent to
// Qux() { _foo = "initialize foo to this!"; }
// but without the extra call to construct an empty string
private:
std::string _foo;
};
So i guess initialization Lists is faster because, it wont call constructor for int( ); and then the operator i=j;
It will directly call i(j);
using the initializer list is faster. can be optimized by the compiler better I believe
- NewStart April 06, 2010