I am wondering if theoretically / practically there is any difference between efficiency and speed of these two codes:
1 2 3 4 5
MyClass a;
for (int i =0; i<N; i++){
a = A[i];
// do some stuff with a
}
versus
1 2 3 4
for (int i =0; i<N; i++){
MyClass a(A[i]);
// do some stuff with a
}
That is if I am using a dummy variable "a" at each iteration is there any speed penalty if the declaration is inside the for loop?
I expect that theoretically there should be since in each iteration the code has to re-declare a variable and then dispose it at the end, but I cannot observe this difference in practice!
Compilers can optimize that a bit
The major difference is this:
method 1: calls constructor once, 9 times operator=, destructor once
method 2: calls 9 times constructor and destructor but never operator=
memory allocation will not affect performance
You can try with a slow constructor | destructor | operator= to see if performance changes
If MyClass has a trivial constructor, copy constructor, assignment operator and destructor, then the compiler will typically optimize the second snippet as you wrote it in the first. However, if MyClass has a non-trivial implementation of one of those four then it cannot make that optimization. The code paths for assignment could differ from calling the constructor/destructor.