How much more efficient is it to declare parameters outside the scope of the loop?

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

+4
source share
2 answers

If it is a primitive type, the compiler will be optimized accordingly.

If it is a custom class, it depends. Which one is more expensive, one extra initialization or destructors BIG_NUMBER ?

Compare these:

 B b; //one initialization for (int i=0; i!=BIG_NUMBER; ++i) { b = arr[i].getB(); //BIG_NUMBER assignments } for (int i=0; i!=BIG_NUMBER; ++i) { B b = arr[i].getB(); //BIG_NUMBER initializations //should be the same as an assignment } //BIG_NUMBER objects destroyed 
+8
source

There is no general answer. It depends on type B, the compiler you are using, and possibly what you do in the loop (after the assignment). All you can do is measure, and even that will tell you about one particular compiler running on one particular machine.

+1
source

All Articles