May too many register variables hurt? (was Re: Novice question.)

Martin Weitzel martin at mwtech.UUCP
Tue Nov 20 03:26:03 AEST 1990


In general, my advice is to use no more than two register variables, and
only in the *outmost* blocklevel in the body of any function.

Why? Listen:

If you have a modern, optimizing compiler, it will ignore the register
keyword and make independent decissions about use of CPU-registers. If
you have modern hardware with many available registers, most probably
you also have a modern compiler, so there's no reason to worry about having
defined "not enough" register variables.

So we can assume that register variables are mostly for software which
may eventually be ported to some unknown ancient compiler that produces
code for some unknown ancient hardware with very few registers. In this
situation, it may in fact hurt performance if you specify too many register
variables, because the compiler may put the wrong ones into the available
registers.

Even if you trust in the compiler implementing correctly what K&R-I mentions,
that the register storage class is obbeyed in the same order as variables
are defined, are you sure how the unknown ancient compiler will interpret
the following example?

	foo()
	{ register int a;
	.... /* some code using a */
	     { register int b;
	     .... /* some code using b */
	     }
	.... /* some more code using a */
	     { register int c;
	     .... /* some code using c */
	     }
        .... /* some more code using a */
        }

Take some ancient CPU with two registers available for local int-s.
The order in which the variables are declared is a-b-c, so c will not
profit from its storage class. Or rather, will the compiler generate
some code to safe one register on each entry to the block defining c?
Will it eventually even do so for the block defining b? (Furthermore,
don't forget that it may require more instructions to call another
function if either the called or the calling funktion has register
variables, because the used CPU-registers must be saved%.)

Of course, if you know your particular compiler/CPU-combination well and
if you accept that your performance-gain may well be a performance-loss
in case the program is ported to anywhere else, you may carefully
investigate which variables to put into registers to achieve the best
performance.

========================
%:I think there is more than one approach of delegating the responsibility
  for saving registers, so you can not tell exactly where the overhead
  will occur.
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.lang.c mailing list