3.5.2 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.

Whenever you have a loop or condition code, use a “strong” stop condition, i.e., the following:

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.

In some situations, using a loop counter that decrements to zero is more efficient than one that starts at zero and counts up by the same number of iterations. So you might be able to rewrite the above as:

for(i=10; i!=0; i--)

Ensure that you enable all the optimizations allowed for the edition of your compiler. If you have a Pro edition, you can use the -Os option (see 5.7.7 Options for Controlling Optimization) to optimize for size. Otherwise, pick the highest optimization available.

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.