This is a mirror of official site: http://jasper-net.blogspot.com/

Optimizing C and C++ Code

| Thursday, January 20, 2011
Embedded software often runs on processors with limited computation power, thus optimizing the code becomes a necessity. In this article we will explore the following optimization techniques for C and C++ code developed for Real-time and Embedded Systems.

  • Adjust structure sizes to power of two
  • Place case labels in narrow range
  • Place frequent case labels first
  • Break big switch statements into nested switches
  • Minimize local variables
  • Declare local variables in the inner most scope
  • Reduce the number of parameters
  • Use references for parameter passing and return value for types bigger than 4 bytes
  • Don't define a return value if not used
  • Consider locality of reference for code and data
  • Prefer int over char and short
  • Define lightweight constructors
  • Prefer initialization over assignment
  • Use constructor initialization lists
  • Do not declare "just in case" virtual functions
  • In-line 1 to 3 line functions

Adjust structure sizes to power of two

When arrays of structures are involved, the compiler performs a multiply by the structure size to perform the array indexing. If the structure size is a power of 2, an expensive multiply operation will be replaced by an inexpensive shift operation. Thus keeping structure sizes aligned to a power of 2 will improve performance in array indexing.

Place case labels in narrow range

If the case labels are in a narrow range, the compiler does not generate a if-else-if cascade for the switch statement. Instead, it generates a jump table of case labels along with manipulating the value of the switch to index the table. This code generated is faster than if-else-if cascade code that is generated in cases where the case labels are far apart. Also, performance of a jump table based switch statement is independent of the number of case entries in switch statement.

Read more: EventHelix

Posted via email from Jasper-net

0 comments: