Walter said:
E. Robert Tisdale wrote:
:It's always better
:to create a local variable in the calling function [main]
:and pass it the function.
This is not always better for performance.
If you create a global variable,
especially one with external linkage (instead of file scope)
then the linker may be able to completely resolve
the address of the variable at link time.
Speed of access to the variable then depends on architecture details,
but would usually be either a load of a constant to an address register
followed by an indirection,
or a direct reference to constant address within the instruction
[depending on the instruction set and upon local code optimizations.]
If the variable were used often,
the address would be likely to sit in primary or secondary cache.
The alternative would load the variable once and then pass it in
a number of procedure calls. That could result in a stack push and
a stack pop per call, or could result in the address being stored
in an address register... which might require saving the previous value
of the register. Saving of registers may require a series of stack
operations, or may have an internal write-consequative optimization that
does the work in less time, or may work within a "register stack" that
is internal to the processor with the possibility that one
may need to dump the register stack anyhow if one gets nested too deeply
in calls. If your system can use an internal register stack [e.g., SPARC]
then passing the address around may require only internal processor
operations and thus be quite fast... until the program gets deeply
nested or the routine gets complex enough that the processor needs to
dump the register in order to use the register for other optimizations.
Which is faster? "It depends". The answer requires a fair detail of
the knowledge of the architecture and the ABI.
No.
First of all, the question was about real-time programming
and *not* high performance programming.
They don't really have anything to do with each other.
Second, you can't even measure the difference, if any,
in the time required to access a global variable
versus a function argument.
Finally, using global variables will simply make your program
less modular and more difficult to read, understand and maintain.
This will quickly overwhelm any advantage in performance
that you might possibly achieve by using global variables
instead of passing arguments to functions
whether you are writing program for real-time
or time-sharing environments.