Sometimes, looking at the optimized code, I see that parameters that are used only within the loop have their declaration moved outside the loop.
Something like that:
A arr[BIG_NUMBER]; // .... // for (int i=0; i!=BIG_NUMBER; ++i) { B b = arr[i].getB(); // ... do some work with b. }
turns into this:
A arr[BIG_NUMBER]; // .... // B b; for (int i=0; i!=BIG_NUMBER; ++i) { b = arr[i].getB(); // ... do some work with b. }
Presumably, the reasoning is that we maintain a constant update b . But is that reasonable? And the answer depends on whether B is a primitive type or class?
I would think that although the scope limitations of variables in a for loop might prevent them from being accessed outside the loop, since the contents of the loop exist on the same stack stack, the declaration of โactualโ only happens once.
(NB, I looked at Creating an object in a loop , but I consider this as another matter, since this is about any costs associated with declaring, not initializing.)
EDIT - Improved Header
source share