Code Optimization - Testing Tools

In software development with strict performance requirements, the two important considerations are speed of execution and memory requirements. Writing the code in assembly language increases speed of execution and also results in optimal code. However, maintaining the code written in assembly language is difficult. Hence, the code is generally written in a high level language such as C or C++ and then some portions of the code, which take lot of execution time, are written in assembly. Even while writing the code in a high-level language, code optimization can be done to make the execution faster. Some important code optimization guidelines are given below:

  • Eliminate dead code: Dead code is that portion of the code that will not be executed at all. Novice programmers include such code, declaration and initialization of variable that will not be used at all, use of functions that will not be called at all etc. Profilers help in elimination of dead code.
  • Remove unnecessary debugging code: A lot of code is written during development time for debugging purposes. Unnecessary debugging code needs to be removed. However, note that some debugging code may need to be left out in the final software that helps in debugging the system in the field.
  • Avoid recursion: Recursive functions require a large stack resulting in higher memory requirement. For example, instead of using recursion for calculating a factorial of a number, a better approach is to use a lookup table that will pick up the factorial.
  • Avoid floating-point operations: If necessary, floating-point operations can be converted into fixed-point operations.
  • Use unsigned integers: Use unsigned integer variables wherever possible.
  • Avoid large library routines: To the extent possible, large library routines need to be avoided.
  • Remove loop-invariant code: The code that has no effect on the loop counter is called the loop-invariant code. Consider the example:
  • for(i=0;i<10;++i) { x = 1.0/b; y = x + i; } In this code, the statement x= 1.0/b; is loop-invariant because the value of x is not dependent on the value of i. Hence, this statement can appear above the beginning of the for loop. Otherwise, the value of x is calculated every time resulting in unnecessary execution of a statement.
  • Use the correct optimization level of the compiler: The compiler has an in­built optimizer. Generally, the compilers provide different optimization levels, level 0 to level 3. Level 3 offers the highest optimization. Based on the need, the optimization level can be set.

Note: Elimination of dead code, avoiding recursion, avoiding floating-point operations to the possible extent, avoiding large library routines and removal of loop-invariant statements are some of the important guidelines for code optimization.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Testing Tools Topics