The following simple rules helps the compiler to produce more efficient code.
- Use unsigned variant of integers, whenever possible
- Use int (or char) instead of long, whenever possible
- Prefer
++
to +=
and +=
to +
- Avoid to compute twice the same sub-expression (using operators such as += is a good way to enforce this rule)
- Array access are not very efficient, so prefer to access arrays' content thru pointers.
- Do not hesitate to use structs, they are generally very efficient.
- Do not hesitate to use constant array indexes, they are generally very efficient.
- Using global variables leads to smaller and faster code.
Be careful, it also leads to lack of modularity and memory wasting. See previous section for modularity issue.
- Implement 8 bit left shifts with
products: due to availability of hardware multiplication
the code will be fast. This rule does not apply to right shifts.
- Use switch instead of cascaded if whenever possible. The code will be faster and smaller.
- Prefer unsigned bit fields to signed ones. Signed bit fields need frequent sign extensions which are resource consuming.
- Avoid accessing bit fields from pointers (ie: s->member). This operation involves an indirection which is also resource consuming.
Alain Gibaud
2015-07-09