Speed Performance - declaring variables

Hi,

I don't know if this question was ask before on this forum but I think it's a pretty easy one.

I have many double variables to declare (they could also be float). So I want to know what is faster (for the computer) between

1
2
3
4
double var1, var2, var3;
var1 = 1.23 + 3.45;
var2 = 2.34 + 4.56;
var3 = 3.45 + 5.67;


and

1
2
3
double var1 = 1.23 + 3.45;
double var2 = 2.34 + 4.56;
double var3 = 3.45 + 5.67;


thank you very much
K-Jtan
There is absolutely no difference, a good compiler will produce the same code in both cases.
However, that's only true for the builtin types, for classes the first method would result in a call to the standard constructor and the assignment operator.

Or in other words: always* use the second variant.
In your first illustration, variables are fully declared and then the values are assigned to it. Therefore, it clearly involves 2 operations, variable definition with default initialization (depending upon scope) followed by value assignment. In your second illustration, variables are initialized during definition with the supplied values. Therefore, it eliminates the assignment operation required in your first approach. You may see this for yourself when you create user defined types using classes/structs. In the first case, constructors and assignment operators would be called whereas in the second case only the constructor would be called. It is always better to go with the second approach even though the difference may not be noticeable for default types.
Last edited on
thank you very much.

that fully answers my question
Topic archived. No new replies allowed.