Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ever more efficient to declare parameters outside of a loop's scope?

Sometimes when looking at optimised code, I see that parameters that are used only within the scope of a loop have their declaration moved outside of the loop.

Something like this:

A arr[BIG_NUMBER];

// .... //

for (int i=0; i!=BIG_NUMBER; ++i)
{
    B b = arr[i].getB();
    // ... do some work with b.
}

being turned 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're saving on continually redeclaring b. But is this a reasonable thing to do? And is the answer different depending on whether B is a primitive type or a class?

I would have thought that whilst the scope limitations of the variables within the for loop may prevent them from being accessed outside the loop, as the loop's contents exists within the same stack frame, the 'actual' declaration only happens once.

(NB, I've considered Creating an object in the loop but consider this to be a different question as it is about any costs associated with declaration rather than initialisation.)

EDIT - improved title

like image 333
Tim MB Avatar asked Jan 16 '23 09:01

Tim MB


1 Answers

If it's a primitive type, the compiler will optimize accordingly.

If it's a user-defined class, it depends. What's more expensive, one extra initialization or BIG_NUMBER destructors?

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
like image 69
Luchian Grigore Avatar answered Jan 31 '23 05:01

Luchian Grigore