Variables

Use local variables, preferably automatic variables, as much as possible. The compiler can accurately analyze the use of local variables, but it has to make several worst-case assumptions about global variables. These assumptions tend to hinder optimization. For example, if you write a function that uses external variables heavily, and that function also calls several external functions, the compiler assumes that every call to an external function could change the value of every external variable. If you know that none of the function calls affects the global variables that you are using, and you have to read them frequently with function calls interspersed, copy the global variables to local variables and then use these local variables. The compiler can then perform optimization that it could not otherwise perform.

If you must use global variables, use static variables with file scope rather than external variables wherever 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.

To access an external variable, the compiler has to make an extra memory access to obtain the address of the variable. When the compiler removes extraneous address loads, it has to use a register to keep the address. Using many external variables simultaneously takes up many registers. Those that cannot fit into registers during optimization are spilled into memory. Because all elements of an external structure use the same base address, you should group external data into structures or arrays wherever it makes sense to do so.

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.

Because the compiler treats register variables the same as it does automatic variables, you do not gain anything by declaring register variables. Note that this differs from other implementations, where using the register attribute can greatly affect program performance.



Writing Optimized Code...
    Overview
    Pointers
    Functions
    Function Arguments
    Expressions
    Critical Loops
    Conversions
    Arithmetic Conversions
    Inlined Components