How to write efficent code

The following simple rules helps the compiler to produce more efficient code.

  1. Use unsigned variant of integers, whenever possible
  2. Use int (or char) instead of long, whenever possible
  3. Prefer ++ to += and += to +
  4. Avoid to compute twice the same sub-expression (using operators such as += is a good way to enforce this rule)
  5. Array access are not very efficient, so prefer to access arrays' content thru pointers.
  6. Do not hesitate to use structs, they are generally very efficient.
  7. Do not hesitate to use constant array indexes, they are generally very efficient.
  8. 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.
  9. Implement 8 bit left shifts with $ \times 2$ products: due to availability of hardware multiplication the code will be fast. This rule does not apply to right shifts.
  10. Use switch instead of cascaded if whenever possible. The code will be faster and smaller.
  11. Prefer unsigned bit fields to signed ones. Signed bit fields need frequent sign extensions which are resource consuming.
  12. Avoid accessing bit fields from pointers (ie: s->member). This operation involves an indirection which is also resource consuming.

Alain Gibaud 2015-07-09