Code-Tuning Techniques

Code Complete
Author : Steven C. McConnell.

Prof. Asha N

1
Code-Tuning Techniques




To improve performance in code
Also called as “anti-refactoring”.
Code tuning refers to small-scale changes
rather than changes in larger-scale designs.

Prof. Asha N

2
Code-Tuning Techniques
1.
2.
3.

4.
5.
6.

Logic
Loops
Data Transformations
Expressions
Routines
Recoding in Assembler

Prof. Asha N

3
1. Logic


Stop Testing When You Know the Answer
 if ( 5 < x ) and ( x < 10 ) then ...
With short-circuit evaluation
if ( 5 < x ) then
if ( x < 10 ) then ...


C++ Example of Not Stopping After You Know the Answer
negativeInputFound = False;
for ( i = 0; i < iCount; i++ )
{
if ( input[ i ] < 0 ) {
negativeInputFound = True;
}
}
Prof. Asha N

4
Contd….


Order Tests by Frequency




Arrange tests so that the one that’s fastest and most likely to be true is
performed first. This principle applies to case statements and to chains of ifthen-elses.
Visual Basic Example of a Poorly Ordered Logical Test
Select inputCharacter
Case "+", "="
ProcessMathSymbol( inputCharacter )
Case "0" To "9"
ProcessDigit( inputCharacter )
Case ",", ".", ":", ";", "!", "?"
ProcessPunctuation( inputCharacter )
Case " "
ProcessSpace( inputCharacter )
Case "A" To "Z", "a" To "z"
ProcessAlpha( inputCharacter )
Case Else
ProcessError( inputCharacter )
End Select

Prof. Asha N

5
Contd….


Visual Basic Example of a Well-Ordered Logical Test
Select inputCharacter
Case "A" To "Z", "a" To "z"
ProcessAlpha( inputCharacter )
Case " "
ProcessSpace( inputCharacter )
Case ",", ".", ":", ";", "!", "?"
ProcessPunctuation( inputCharacter )
Case "0" To "9"
ProcessDigit( inputCharacter )
Case "+", "="
ProcessMathSymbol( inputCharacter )
Case Else
ProcessError( inputCharacter )
End Select
Prof. Asha N

6
Contd….


Substitute Table Lookups for Complicated Expressions

Prof. Asha N

7
Contd….
C++ Example of a Complicated Chain of Logic
if ( ( a && !c ) || ( a && b && c ) ) {
category = 1;
}
else if ( ( b && !a ) || ( a && c && !b ) ) {
category = 2;
}
else if ( c && !a && !b ) {
category = 3;
}
else {
category = 0;
}
Prof. Asha N

8
Contd….
C++ Example of Using a Table Lookup to Replace Complicated
Logic

Prof. Asha N

9
Contd….


Use Lazy Evaluation
 Lazy evaluation is similar to just-in-time strategies
that do the work closest to when it’s needed.

Prof. Asha N

10
2. Loops









Un switching
Jamming
Unrolling
Minimizing the Work Inside Loops
Sentinel Values
Putting the Busiest Loop on the Inside
Strength Reduction

Prof. Asha N

11
Contd….


Un switching


putting loops inside the conditional rather than
putting the conditional inside the loop
C++ Example of a Switched Loop

Prof. Asha N

12
Contd….
C++ Example of an Unswitched Loop

Prof. Asha N

13
Contd….


Jamming
 Jamming, or “fusion,” is the result of combining two loops that
operate on the same set of elements. The gain lies in cutting the
loop overhead from two loops to one.




For i = 0 to employeeCount - 1
employeeName( i ) = ""
Next
...
For i = 0 to employeeCount - 1
employeeEarnings( i ) = 0
Next
For i = 0 to employeeCount - 1
employeeName( i ) = ""
employeeEarnings( i ) = 0
Next
Prof. Asha N

14
Contd….


Unrolling


The goal of loop unrolling is to reduce the amount of loop housekeeping




Java Example of a Loop That Can Be Unrolled
i = 0;
while ( i < count ) {
a[ i ] = i;
i = i + 1;
}

Java Example of a Loop That’s Been Unrolled Once
i = 0;
while ( i < count - 1 ) {
a[ i ] = i;
a[ i + 1 ] = i + 1;
i = i + 2;
}
if ( i == count ) {
a[ count - 1 ] = count - 1;
}

Prof. Asha N

15
Contd….


Minimizing the Work Inside Loops




for ( i = 0; i < rateCount; i++ ) {
netRate[ i ] = baseRate[ i ] * rates->discounts->factors->net;
}
quantityDiscount = rates->discounts->factors->net;
for ( i = 0; i < rateCount; i++ ) {
netRate[ i ] = baseRate[ i ] * quantityDiscount;
}

Prof. Asha N

16
Contd….


Sentinel Values
 When you have a loop with a compound test, you can often save
time by simplifying the test
found = FALSE;
i = 0;
while ( ( !found ) && ( i < count ) ) {
if ( item[ i ] == testValue ) {
found = TRUE;
}
else {
i++;
}
}
if ( found ) {
...
Prof. Asha N

17
Contd….


Putting the Busiest Loop on the Inside
for ( column = 0; column < 100; column++ ) {
for ( row = 0; row < 5; row++ ) {
sum = sum + table[ row ][ column ];
}
}

Prof. Asha N

18
Contd….


Strength Reduction


Reducing strength means replacing an expensive
operation such as multiplication with a cheaper
operation such as addition

Prof. Asha N

19
3. Data Transformations








Use Integers Rather Than Floating-Point
Numbers
Use the Fewest Array Dimensions
Possible
Minimize Array References
Use Supplementary Indexes
String-Length Index
Independent, Parallel Index Structure
Use Caching
Prof. Asha N

20
4. Expressions









Exploit Algebraic Identities
Use Strength Reduction
Initialize at Compile Time
Be Wary of System Routines
Use the Correct Type of Constants
Precompute Results
Eliminate Common Subexpressions

Prof. Asha N

21
5. Routines



the most powerful tools in code tuning is a
good routine decomposition
Rewrite Routines In Line

Prof. Asha N

22
6. Recoding in Assembler



Recoding in assembler tends to improve both speed
and code size
typical approach to optimizing with assembler
1. Write 100 percent of an application in a high-level language.
2. Fully test the application, and verify that it’s correct.
3. If performance improvements are needed after that, profile the
application to identify hot spots. Since about 5 percent of a
program usually accounts for about 50 percent of the running
time, you can usually identify small pieces of the program as
hot spots.
4. Recode a few small pieces in assembler to improve overall
performance.
Prof. Asha N

23

Code tuning techniques

  • 1.
    Code-Tuning Techniques Code Complete Author: Steven C. McConnell. Prof. Asha N 1
  • 2.
    Code-Tuning Techniques    To improveperformance in code Also called as “anti-refactoring”. Code tuning refers to small-scale changes rather than changes in larger-scale designs. Prof. Asha N 2
  • 3.
  • 4.
    1. Logic  Stop TestingWhen You Know the Answer  if ( 5 < x ) and ( x < 10 ) then ... With short-circuit evaluation if ( 5 < x ) then if ( x < 10 ) then ...  C++ Example of Not Stopping After You Know the Answer negativeInputFound = False; for ( i = 0; i < iCount; i++ ) { if ( input[ i ] < 0 ) { negativeInputFound = True; } } Prof. Asha N 4
  • 5.
    Contd….  Order Tests byFrequency   Arrange tests so that the one that’s fastest and most likely to be true is performed first. This principle applies to case statements and to chains of ifthen-elses. Visual Basic Example of a Poorly Ordered Logical Test Select inputCharacter Case "+", "=" ProcessMathSymbol( inputCharacter ) Case "0" To "9" ProcessDigit( inputCharacter ) Case ",", ".", ":", ";", "!", "?" ProcessPunctuation( inputCharacter ) Case " " ProcessSpace( inputCharacter ) Case "A" To "Z", "a" To "z" ProcessAlpha( inputCharacter ) Case Else ProcessError( inputCharacter ) End Select Prof. Asha N 5
  • 6.
    Contd….  Visual Basic Exampleof a Well-Ordered Logical Test Select inputCharacter Case "A" To "Z", "a" To "z" ProcessAlpha( inputCharacter ) Case " " ProcessSpace( inputCharacter ) Case ",", ".", ":", ";", "!", "?" ProcessPunctuation( inputCharacter ) Case "0" To "9" ProcessDigit( inputCharacter ) Case "+", "=" ProcessMathSymbol( inputCharacter ) Case Else ProcessError( inputCharacter ) End Select Prof. Asha N 6
  • 7.
    Contd….  Substitute Table Lookupsfor Complicated Expressions Prof. Asha N 7
  • 8.
    Contd…. C++ Example ofa Complicated Chain of Logic if ( ( a && !c ) || ( a && b && c ) ) { category = 1; } else if ( ( b && !a ) || ( a && c && !b ) ) { category = 2; } else if ( c && !a && !b ) { category = 3; } else { category = 0; } Prof. Asha N 8
  • 9.
    Contd…. C++ Example ofUsing a Table Lookup to Replace Complicated Logic Prof. Asha N 9
  • 10.
    Contd….  Use Lazy Evaluation Lazy evaluation is similar to just-in-time strategies that do the work closest to when it’s needed. Prof. Asha N 10
  • 11.
    2. Loops        Un switching Jamming Unrolling Minimizingthe Work Inside Loops Sentinel Values Putting the Busiest Loop on the Inside Strength Reduction Prof. Asha N 11
  • 12.
    Contd….  Un switching  putting loopsinside the conditional rather than putting the conditional inside the loop C++ Example of a Switched Loop Prof. Asha N 12
  • 13.
    Contd…. C++ Example ofan Unswitched Loop Prof. Asha N 13
  • 14.
    Contd….  Jamming  Jamming, or“fusion,” is the result of combining two loops that operate on the same set of elements. The gain lies in cutting the loop overhead from two loops to one.   For i = 0 to employeeCount - 1 employeeName( i ) = "" Next ... For i = 0 to employeeCount - 1 employeeEarnings( i ) = 0 Next For i = 0 to employeeCount - 1 employeeName( i ) = "" employeeEarnings( i ) = 0 Next Prof. Asha N 14
  • 15.
    Contd….  Unrolling  The goal ofloop unrolling is to reduce the amount of loop housekeeping   Java Example of a Loop That Can Be Unrolled i = 0; while ( i < count ) { a[ i ] = i; i = i + 1; } Java Example of a Loop That’s Been Unrolled Once i = 0; while ( i < count - 1 ) { a[ i ] = i; a[ i + 1 ] = i + 1; i = i + 2; } if ( i == count ) { a[ count - 1 ] = count - 1; } Prof. Asha N 15
  • 16.
    Contd….  Minimizing the WorkInside Loops   for ( i = 0; i < rateCount; i++ ) { netRate[ i ] = baseRate[ i ] * rates->discounts->factors->net; } quantityDiscount = rates->discounts->factors->net; for ( i = 0; i < rateCount; i++ ) { netRate[ i ] = baseRate[ i ] * quantityDiscount; } Prof. Asha N 16
  • 17.
    Contd….  Sentinel Values  Whenyou have a loop with a compound test, you can often save time by simplifying the test found = FALSE; i = 0; while ( ( !found ) && ( i < count ) ) { if ( item[ i ] == testValue ) { found = TRUE; } else { i++; } } if ( found ) { ... Prof. Asha N 17
  • 18.
    Contd….  Putting the BusiestLoop on the Inside for ( column = 0; column < 100; column++ ) { for ( row = 0; row < 5; row++ ) { sum = sum + table[ row ][ column ]; } } Prof. Asha N 18
  • 19.
    Contd….  Strength Reduction  Reducing strengthmeans replacing an expensive operation such as multiplication with a cheaper operation such as addition Prof. Asha N 19
  • 20.
    3. Data Transformations        UseIntegers Rather Than Floating-Point Numbers Use the Fewest Array Dimensions Possible Minimize Array References Use Supplementary Indexes String-Length Index Independent, Parallel Index Structure Use Caching Prof. Asha N 20
  • 21.
    4. Expressions        Exploit AlgebraicIdentities Use Strength Reduction Initialize at Compile Time Be Wary of System Routines Use the Correct Type of Constants Precompute Results Eliminate Common Subexpressions Prof. Asha N 21
  • 22.
    5. Routines   the mostpowerful tools in code tuning is a good routine decomposition Rewrite Routines In Line Prof. Asha N 22
  • 23.
    6. Recoding inAssembler   Recoding in assembler tends to improve both speed and code size typical approach to optimizing with assembler 1. Write 100 percent of an application in a high-level language. 2. Fully test the application, and verify that it’s correct. 3. If performance improvements are needed after that, profile the application to identify hot spots. Since about 5 percent of a program usually accounts for about 50 percent of the running time, you can usually identify small pieces of the program as hot spots. 4. Recode a few small pieces in assembler to improve overall performance. Prof. Asha N 23