3.5. Code optimization
3.5. 1. Introduction to code optimization
Code optimization is the process of modifying software so that it executes more efficiently while maintaining the same required functionality.
The objective may be to reduce:
- Execution time
- Memory usage
- CPU utilization
- Power consumption
- Program size
3.5.2. Common code optimization techniques
1. Remove unnecessary code
Unused functions, variables, and statements should be removed.
2. Avoid repeated calculations
Instead of:
result = a * b + c;
Being calculated repeatedly when the values do not change, calculate it once and store the result.
3. Use efficient loops
Poorly designed loops can consume significant processing time.
4. Use appropriate data structures
The data structure should match the problem.
5. Avoid unnecessary delays
For example:
delay(5000);
May unnecessarily stop the processor for five seconds.
6. Use interrupts
Interrupts can allow the processor to respond to events without continuously checking them.
7. Use compiler optimization
Many embedded compilers provide optimization levels such as:
-O0 , -O1 , -O2 , -O3
Higher optimization levels can reduce execution time or program size, although the exact effect depends on the compiler and application.
Example
An inefficient approach:
while(1) {
check_button();
delay(100);}
A better real-time design may use an interrupt to detect the button event.
Important consideration
Code optimization should not sacrifice correctness.
A program that is faster but produces incorrect results is not a successful optimization.


