Hi all, I have a general question that probably doesn't have a single answer.
In the frequent occasion in which you have a variable that is used temporarily in a loop, is it more efficient to declare it in the loop or outside?
e.g. do this
1 2 3 4 5
for (int i=0; i<n; i++)
{
int temp;
; some processing that uses temp as an intermediate step
}
or this
1 2 3 4 5
int temp;
for (int i=0; i<n; i++)
{
; some processing that uses temp as an intermediate step
}
Either way temp will be on the stack. The first is better in terms of making the scope of temp clear, but the second seems as if it avoids some repeated allocation step.
My knowledge of exactly what goes on under the hood of compilers is not great, and I assume that's what is needed to answer this.
Of course you can always try both and profile the code, but this kind of thing happens all the time so it would be nice to know in advance if there is a good rule of thumb about which is more efficient (if it makes any difference, and if it doesn't the first method is better from a code style POV).
For basic types like int it makes absolutely no difference. I'd go with the former because it keep the scope clear.
For complex types (like string) you're probably better off with the latter (putting it outside the loop). The reason for that is because classes like string will deallocate when their dtor is run, then reallocate memory later when the loop is run again.