When declaring primitives does it matter if I use the assignment operator or copy constructor? Which one gives the optimal performance, or do most compilers today compile these two statements to the same machine code?
int i = 1;
int j( 1 );
When declaring primitives does it matter if I use the assignment operator or copy constructor? Which one gives the optimal performance, or do most compilers today compile these two statements to the same machine code?
int i = 1;
int j( 1 );
I'm fairly certain that they are the same, however if you do a static initialization, there is no initialization during runtime, the value is built into the binary.
static int i = 1;
Though, this isn't always appropriate, given the meaning of the keyword static.
Same for:
int i = 1;
int j( 1 );
Not for:
Cat d;
Cat c1;
c1 = d;
Cat c2(d);//<-- more efficient
Me think both will be compiled the same; just use the one you feel is the most readable for you and other who might read your code.
In general, this question can't be answered. For primitive types a good compiler will reduce them to the same Assembly instructions, but for user-defined types (which is to say, classes) you're at the mercy of whoever wrote the copy and assignment operators. I've seen code where one was faster than the other by an order of magnitude, because the person who wrote the copy constructor wasn't the same as the person who wrote the assignment operator -- and one of them did it smart and one of them didn't.
In the case of a single primitive type it's not going to matter.
When it can matter is when you have an aggregate of primitive types. In other words, a POD. In that case, there is no more efficient way to instantiate it that by using the aggregate initializer syntax:
struct POD
{
int n;
double d;
bool b;
};
If that's your POD, then this:
POD pod = {1, 3.14, true};
...can't be beat in terms of efficiency.