Simple tricks, tested with the compiler, to help you write more efficient C code
1. Keep Mathematical Expressions As Short As Possible: Break complex expressions into simpler ones to save program memory.
2. Datatype: Use unsigned values instead of signed values if possible. Avoid unnecessary type conversions.
3. Use Efficient Algorithms: e.g. using a hash table instead of a linear search can improve performance when searching for a value in a large data set.
4. Avoid Using Switch Statements: Using if statements can reduce memory usage compared to switch statements.
5. Avoid Else in If Statements: Assume frequent conditions first to minimize code size.
6. Use One-Dimensional Arrays: Convert two-dimensional arrays into one-dimensional arrays for better memory utilization.
7. Avoid use of Floats: Perform computations with integers and convert to float only when necessary.
8. Simplify for Loops: Reduce loop memory usage by simplifying the loop control statements.
9. Rework Mathematical Expressions: Use division instead of multiplication with constants whenever possible. e.g instead of multiplying the number by 0.1, you can divide number by 10
10. Rearrange If Conditions: Simplify conditions inside if statements to reduce code size.
11. Minimize branching: Branching can increase the execution time, try to minimise the branching when possible
12. Use of Inline function: Inline functions can help to increase the performance
By implementing these tricks, you can optimize your code for embedded systems, making your programs more efficient and saving valuable memory space.
Here are few reference documents available from Microchip and TI. Refer below link to download the files: