Tuesday, August 14, 2007

Optimization in C

* Better Algorithm or Data Structure

* Mathematics Solution
- Get correct mathematics formula for the problem. For example, calculate N!.

* More Space Less Time
- Using macros for short functions
- Look-up Table

* Use Bit Operations (Be cautious)
- Shift and bit mask for division and module

* Language and compiler features
- Use pointer to operate an array
- No need to define useless return value
- Define a variable in the register instead of stack by using `register'
- Prefer post ++/-- to prefix ++/-- for usage without reference to the result
- Organize the order of cases in switch: The higher occurrence the higher its case number
- In some cases, an array of pointer to functions might be more efficient than switch statement. For example,
int handleMsg1(void);
int handleMsg2(void);
int handleMsg3(void);
int (*MsgFunction[])() = {handleMsg1, handleMsg2,handleMsg3};
status = MsgFunction[ReceiveMessage()]();

* Hardware features
- Copy codes and data from FLASH to RAM for running
- Fully use the UART buffer for data transfer
- Use DMA

* Embed Assembly
- However, it is non-portable

No comments: