Lexical variables - speed penalty?

J

Joakim Hove

Hello,

i have a quite large and unwieldy function with *many* local
variables. The various variables are typically only used in small
parts of the function, and I would like to define them locally:


double function () {

double gvar1,gvar2;

{
double var1,var2;

/* Code doing something with var1 and var2 */

}

/* Code accessing the function-global variables gvar1 and gvar2 */

{
double var3,var4;

/* Code working on var3 and var4 */

}

}


The code path is deterministic, and all blocks will be executed. Now,
my question is wether there is a hit in execution speed by doing it
like this?


Regards

Joakim
 
R

Richard Tobin

Joakim Hove said:
The code path is deterministic, and all blocks will be executed. Now,
my question is wether there is a hit in execution speed by doing it
like this?

No, a good compiler will re-use the same registers for variables with
different scopes (assuming it has enough registers anyway). There's
no reason for it to produce code any different from what you'd get if
you re-used variables yourself, and in some (rare) cases it may even
produce better code because it can be sure about when the values are
no longer required.

-- Richard
 
M

Malcolm

Joakim Hove said:
i have a quite large and unwieldy function with *many* local
variables. The various variables are typically only used in small
parts of the function, and I would like to define them locally:
Probably there won't be any difference in execution speed. This is because
compilers typically set up the stack frame at the beginning of each
function, not for each block. So your variables local to the block are just
expanded to function variables.
There is naturally no guarantee.
 
C

CBFalconer

Joakim said:
i have a quite large and unwieldy function with *many* local
variables. The various variables are typically only used in small
parts of the function, and I would like to define them locally:

You should break it up into multiple functions. It will read much
better, and can even generate the same code if you use the inline
directive (C99 and gcc).

Doing that can also handle the local initializations, because
function parameters are just initialized local variables. So many
of the variables should disappear. The paramatization and breakup
may well identify common code subsets.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top