C– – Efficiency

repetition), but for loops are implemented with much greater overhead (one conditional jump and three unconditional jumps per repetition.) For this reason, it is best to replace for loops with while loops. (This was not done in the example projects for the sake of readability and to provide an example of a C–– for loop.) If the number of repetitions is both fixed and small, the code will execute faster if the loop is unwrapped. Switch statements and if-else blocks have similar overhead. Switch statements are slightly more efficient because the values being compared are only looked up once, while an if-else block looks up the values for each comparison. Switch statements do not use a table lookup; they use a fall through structure like an if-else block. Because of the fall through structure of switch and if-else blocks, items occurring first are executed with less overhead than items occurring last. If it is known that certain cases will occur more frequently than others, the code will execute fastest if the most frequently occurring cases are put before the less frequently occurring ones.

Space for global variables is allocated at compile time. Space for local variables is allocated on the stack at run time. This means that the compiler will not generate a warning if local variables exceed the available RAM. The compiler will generate an error message if the global variables exceed the available RAM. Caution must be used to avoid overflowing the stack by allocating too many local variables. During a call, parameters, return address, local variables, and the frame pointer are stored on the stack using a stack frame. The stack frame structure allows recursive calls, but the elegant solution provided by a recursive program is often offset by inefficiency. Using recursive calls is not recommended with the C–– compiler.

Dividing the program into too many functions can be inefficient also. It may be stylish to separate portions of the program into functions based on what they are designed to do, but unless the functions will be used in multiple places in the program, it is better not to make a function call. There is a tradeoff between ROM usage and RAM usage depending on the number of times a function will be needed. Using a function call requires more RAM and instruction overhead. Not using a function call can require more ROM depending on the size of the function and the number if times it is used.

5-38

Page 334
Image 334
Texas Instruments MSP50C6xx manual Efficiency