Consider the following guidelines:
- Use local variables, preferably automatic variables, as much as
possible.
The compiler must make several worst-case
assumptions about global variables. For example, if a function uses
external variables and also calls external functions, the compiler
assumes that every call to an external function could change the value
of every external variable. If you know that a global variable is
not affected by any function call, and this variable is read several
times with function calls interspersed, copy the global variable to
a local variable and then use this local variable.
- If you must use global variables, use static variables with file
scope rather than external variables whenever possible. In a file
with several related functions and static variables, the optimizer
can gather and use more information about how the variables are affected.
- If you must use external variables, group external data into structures
or arrays whenever it makes sense to do so. All elements of an external
structure use the same base address.
- The #pragma isolated_call preprocessor directive
can improve the runtime performance of optimized code by allowing
the compiler to make less pessimistic assumptions about the storage
of external and static variables. Isolated call functions with constant
or loop-invariant parameters can be moved out of loops, and multiple
calls with the same parameters can be replaced with a single call.
- Avoid taking the address of a variable. If you use
a local variable as a temporary variable and must take its address,
avoid reusing the temporary variable for a different purpose. Taking
the address of a local variable can inhibit optimizations that would
otherwise be done on calculations involving that variable.
- Use constants instead of variables where possible. The optimizer
is able to do a better job reducing runtime calculations by doing
them at compile time instead. For instance, if a loop body has a constant
number of iterations, use constants in the loop condition to improve
optimization (for (i=0; i<4; i++) can be better
optimized than for (i=0; i<x; i++)).
- Use register-sized integers (long data type)
for scalars. For large arrays of integers, consider using one- or
two-byte integers or bit fields.
- Use the smallest floating-point precision
appropriate to your computation. Use the long
double data type only when high precision is required.