Dash
Dash

Reputation: 1

Best way to declare intermediate variables in a loop

I stumbled upon a piece of code I am using frequently which consists in doing arithmetic operations within a loop to update a quantity. The important bit is that I am using intermediate quantity independent from the loop index. I figured out two ways of writing it. In this mock example, I use scalars and vectors but I suppose this applies to virtually every quantity updated using a loop:

scalar coef = someComplicatedScalar;
for (i=0; i<n; i++) {
   vector someComplicatedVector;
   stuff[i] = someComplicatedScalar * someComplicatedVector;
}

or

scalar coef = someComplicatedScalar;
vector someComplicatedVector;
for (i=0; i<n; i++) {
   stuff[i] = someComplicatedScalar * someComplicatedVector;
}

During development, I mostly do the first one. I was wondering if it is worth moving from the first to the second implementation during code cleaning. My concern is about optimisation because as C++ cannot create new variables at runtime and I am afraid it creates a bunch of useless copies.

Note: I am using a C++ framework hence the use of alternative classes.

Upvotes: 0

Views: 229

Answers (1)

Ravi Prakash
Ravi Prakash

Reputation: 313

The compiler will automatically optimize your code if it find an expression or operation invariant of the loop.

But for the shake of explicit optimization you can put all the expressions and instantiation of local variables which are invariant of the loop outside of the loop. This will be the well optimized code.

Upvotes: 1

Related Questions