3.5.1 How Can I Make My Code Smaller?
There are a number of ways that this can be done, but results vary from one project to the next. Use the assembly list file to observe the assembly code produced by the compiler to verify that the following tips are relevant to your code. For information on the list file, see the MPLAB® XC32 Assembler, Linker and Utilities User’s Guide (DS50002186).
Use the smallest data types possible as less code is needed to access
these (which also reduces RAM usage). For examples, a short integer type
exists for this compiler. See Supported Data Types and Variables for all data types and sizes.
There are two sizes of floating-point type, as well, and these are discussed in the same section. Replace floating-point variables with integer variables wherever possible. For many applications, scaling a variable's value makes eliminating floating-point operations possible.
Use unsigned types, if possible, instead of signed types, particularly if they are used in expressions with a mix of types and sizes. Try to avoid an operator acting on operands with mixed sizes whenever possible.
for(i=0; i!=10; i++)is
preferable to:for(i=0; i<10; i++)A check for equality (== or !=) is
usually more efficient to implement than the weaker < comparison.
for(i=10; i!=0; i--)Choose the highest optimization level, -Os. See Options for Controlling Optimization.
Consider using the Thumb compressed instruction set by using the -mthumb
option.
Be aware of what optimizations the compiler performs so you can take advantage of them and don’t waste your time manually performing optimizations in C code that the compiler already handles, e.g., don’t turn a multiply-by-4 operation into a shift-by-2 operation as this sort of optimization is already detected.
