Code Book 2 Reading Notes 15-Chapter 26 code-tuning techniques

Source: Internet
Author: User

Chapter 26 code-tuning techniques
 CodeAdjustment Technology

26.1 Logic
· Stop testing when you know the answer stops judgment after knowing the answer
For example, use a loop to find the first negative value in an array and then use break to stop the loop.
· Order tests by Frequency Adjust the order of judgment based on the frequency of occurrence
Arrange the order of judgment so that the fastest and most likely true judgment is first executed. That is to say, let

It is easier to go into common processing. If there is an inefficient situation, it should appear when the processing is very common.
This principle applies to case statements and if-then-else statement strings.
· Compare performance of similar logic structures Performance Comparison between similar logical structures
The case and if-then-else statements may be more efficient in any way considering the differences in the development environment.
In short, there is nothing to replace the measurement conclusion.
· Substitute table lookups for complicated expressions replace complex expressions with query tables
Chapter 2 detailed descriptions of how to replace complex logic with the table-driven method.
Using a query table is more efficient than moving through a complex Logical Link.
· Use lazy evaluation evaluate using inertia
The value of inertia is similar to the instant completion Policy (just-in-time), that is, it is processed only when the work must be completed.
Example: assume that yourProgramThere is a table with 5000 values. The program generates this table at startup and then runs

Use it in the row. If the program only uses a small part of the entire table, it is better than calculating all the content in the table at the beginning.

When necessary. Once an entry is computed, it can still be stored for later use (the so-called "cache ").

26.2 loops Loop
· Unswitching
The word switching refers to the judgment in the loop, which is executed in each loop.
If a judgment result does not change during loop running, you can refer this judgment to the outside of the loop to avoid repeating

Judgment.
For (I = 0; I <count; I ++ ){
If (sumtype = sumtype_net ){
Netsum + = amount [I];
}
Else {
Grosssum + = amount [I];
}
}
This Code repeats the if test statement every time, even though it gets the same value throughout the loop. It should be rewritten:
If (sumtype = sumtype_net ){
For (I = 0; I <count; I ++ ){
Netsum + = amount [I];
}
}
Else {
For (I = 0; I <count; I ++ ){
Grosssum + = amount [I];
}
}

· Jamming merge
Jamming or fusion means to combine two cycles of operations on the same group of elements. This action

The benefit is to reduce the total overhead of two cycles to the overhead of a single loop.
Loop merge has two major risks. First, the two cycles to be merged may be changed under their respective labels.

Cycle subscript. Secondly, you may not be able to merge loops so easily. Before merging, make sure that

The order of other codes is still correct.

· Unrolling Expansion
The purpose of loop expansion is to reduce the work required to maintain the cycle.

· Minimizing the work inside loops reduces the work done within the loop as much as possible
The key to writing efficient loops is to minimize the internal work of loops.
This is a good programming practice and can improve the readability of the program in many cases.
For (I = 0; I <ratecount; I ++)
{
Netrate [I] = baserate [I] * rates-> discounts-> factors-> net;
}
In this case, the complex pointer expression is assigned to a variable with the correct name, which not only improves the readability of the code, but also improves the code performance.

.
Quantitydiscount = rates-> discounts-> factors-> net;
For (I = 0; I <ratecount; I ++)
{
Netrate [I] = baserate [I] * quantitydiscount;
}

· Sentinel values sentinel Value
When the cyclic condition is a compound judgment, you can simplify the judgment to save the code running time. If this loop is a search

Loop. One of the simplified methods is to use sentinel value ).
You can put it at the end of the loop range to ensure that the loop can be terminated.
--------------------------------------
Found = false;
I = 0;
While ((! Found) & (I <count )){
If (item [I] = testvalue ){
Found = true;
}
Else {
I ++;
}
}
If (found ){...}
---------------------------------------
In this Code, we need to judge every loop iteration! Found And I <count. The former determines whether the required elements are found; the latter avoids

The ring exceeds the end of the array.
Inside the loop, each item must be determined separately. Therefore, for each iteration, there are actually three judgments in the loop.
---------------------------------------
Use the Sentinel value for loop:
Intialvalue = item [count];
Item [count] = testvalue;
I = 0;
While (item [I]! = Testvalue ){
I ++;
}
// Check if value was found
If (I <count ){...}
---------------------------------------
Place the sentry value at the end of the array to store testvalue. So that each loop can be judged only once.
If I does not reach the Sentinel value at the end, it indicates that the value to be searched is found.
In fact, you can use the Sentinel method-from the linked list to the array-in any case where linear search is used.
Note that you must carefully read the value and put it into the data structure.

· Putting the busiest loop on the inside place the busiest loop in the innermost layer
When nesting loops, you need to consider which loop is placed outside and which one is placed inside. For example, the following example of loop nesting is modified.

.
For (column = 0; column <100; column ++ ){
For (ROW = 0; row <5; row ++ ){
Sum = sum + Table [row] [column];
}
}
The key to improvement is to solve the problem that the number of execution of the outer loop is much higher than that of the inner loop. During each execution, the cycle starts

Convert the circular subscript. After executing the circular code, increment it and check it.
The total number of cycles is 100 external cycles, 100x5 means 500 internal cycles, a total of 600.
If the internal and external loops are exchanged, five external loops will be performed. 5*100 means 500 internal loops, a total of 505.
Through analysis, you expect this will save (600-505)/600, that is, 16% of the time. After the actual measurement, there will be more.

· Strength reduction intensity
Reducing the intensity means that multiple lightweight operations (such as addition) are used to replace a costly operation (such as multiplication ).
VB example: multiply the circular subscript
For I = 0 to salecount-1
Commission (I) = (I + 1) * Revenue * basecommission * discount
Next
This code is simple and clear, but it is costly. The product is obtained through accumulation, rather than computing each time.
VB example: add without multiplication
Incremetalcommission = revenue * basecommission * discount
Cumulativecommission = incremetalcommission
For I = 0 to salecount-1
Commission (I) = cumulativecommission
Cumulativecommission = cumulativecommission + incrementalcommission
Next

26.3 data transformation
· Use integers rather than floating-point numbers
Use an integer instead of a floating point number.
The addition and multiplication of integer numbers are much faster than those of floating-point numbers. Therefore, for example, changing the circular subscript from the floating point type to an integer type

This method can save a lot of time for code running.

· Use the fewest array dimensions possible array with as few dimensions as possible
The accumulated programming wisdom over the years shows that the cost of processing multi-dimensional arrays is astonishing.
The optimization results in VB and Java languages are obvious. However, C ++ and C # have almost no optimization results, so they do not need to be harsh.

· Minimize array references: Minimize array references
Reducing access to arrays is always beneficial. For example, if you frequently access array [I] in a piece of code, you can optimize it into a local variable (

Array [I]). replace all the places where array [I] is used with this local variable.

· Use supplementtary indexes to use secondary Indexes
Using secondary indexes means adding relevant data to make access to certain data more efficient.
1. String-Length Index String Length Index
You can find secondary indexes in different string storage policies. In C, the string is 0

In bytes. For a VB string, a Length byte is hidden at the beginning of each string, indicating the length of the string.

. To determine the length of a C string, the program needs to count each byte from the start of the string, until the byte with the found value of 0 is known.

. To determine the length of the VB string, the program only needs to look at the length bytes.
The Length byte of VB is an example. It indicates that adding an index to the data structure may lead to some specific operations-for example

Calculate the length of a string -- get faster.
You can apply this idea of adding indexes to the length to any variable-length data type. When you need to know the data

It is more effective to maintain the structure length data earlier than the temporary calculation.
2. Independent, parrllel index structure Independent Parallel Index Structure
Sometimes, the index of the operation data type is more effective than the operation data type itself. Especially if the data type is

The index sorting and searching operations are faster than directly performing the same operation on the data.

· Use caching
The Caching mechanism is to save some values so that the most commonly used values are easier to obtain than the less commonly used values.
In addition to caching records on disks, the cache mechanism can be applied to other fields. In MS Windows

In sequence, the performance bottleneck is to obtain the character width when each character is displayed. Cache the recently used character width

Then, the display speed is doubled.
The success of caching depends on the operations related to accessing cached elements, creating Uncached elements, and saving new elements in the cache.

. Generally, if the higher the cost of creating new elements, the more requests with the same information, the more valuable the cache will be. Same

The lower the overhead of accessing the cache element or placing the new element into the cache, the greater the value of the cache.
Like other optimization technologies, caching increases Program Complexity and makes programs more prone to errors.

26.4 Expressions expression
· Exploit algebraic identities Use algebraic equations
You can replace complex operations with low-cost operations by Using Algebraic constants. For example, the following two expressions are logically equivalent.
Not a and not B
Not (A or B)
If you select the second expression, you can avoid a not operation.
Although it may be insignificant to avoid executing a not operation, this general principle is powerful.
Jon Bentley once described a program that judges SQRT (x) <SQRT (y. Because only when x <Y, SQRT

(X) <SQRT (Y). Therefore, we can use x <Y to replace the previous judgment. Because SQRT () is costly, you can predict this.

The results are exciting.

· Use strength limit ction to weaken the computing strength
Possible alternatives:
1. Use addition instead of multiplication
2. Use multiplication instead of Power Multiplication
3. Use a triangle constant to replace an equivalent trigonometric function
4. Use long or int to replace Longlong integers.
5. Replace floating point with the number of fixed points or integer values
6. Replace the double precision with the single precision number.
7. Use the shift operation to replace integer multiplication 2 or Division 2.

· Initialize at compile time initialization during compilation

· Be wary of system routines be careful with system functions

· Use the correct type of constants to use the correct constant type
The specified constant and the variable to be assigned must be of the same type. When the types of constants and related variables are not

When the constants are consistent, the compiler has to convert the types of constants before assigning them to the variables.

· Precompute Results Pre-calculated results
The pre-computed optimization program can take the following forms:
1. Calculate the result before executing the program, write the result into a constant, and assign a value during compilation;
2. Calculate the results before the program is executed, and then hard-code them into the variables used at runtime;
3. Calculate the result before the program execution, store the result in a file, and load it at runtime;
4. When the program starts, all results are calculated at one time and referenced whenever needed.
5. Calculate the number before the cycle starts to minimize the amount of work that needs to be done inside the cycle.
6. Calculate the result for the first time and save the result for later use.

· Eliminate common subexpressions
If you find that an expression always appears in front of you, assign it to a variable and reference it as needed.

Quantity.

26.5 routines subroutine
One of the major tools for code adjustment is good subprogram decomposition.
· Rewrite routines inline rewrite the subroutine to inline
In the early stages of computer programming history, calling subroutines on some machines may seriously affect performance. Subroutine Adjustment

This means that the operating system needs to swap out the program memory, replace it with a sub-program directory, replace it with a specific sub-program, and execute the sub-program,

Then, replace the subroutine and finally return the called subroutine. All these exchange operations consume a large amount of resources,

Slow down the program.
For today's computers, it is much less costly to call a sub-program. Not because you have called a subroutine.

And open a penalty ticket.

26.6 recoding in a low-level language rewrite code in a low-level language
There is an old saying that when a program encounters a performance bottleneck, you should rewrite the code in a low-level language.
If the program is written in C ++, the lower-level language may be assembly; if the program is written in Python, the lower-level language may be C.
Code re-writing in low-level languages is more likely to improve speed and reduce code size.
There is a relatively simple and effective method to assemble and recode, that is, to enable a compiler that can output a list of assembly code. Set

You need to adjust the compilation code of the sub-program to extract it and save it to a separate source file. Using this assembly code as the basis for optimization,

Manually adjust the code, check the correctness of the Code in each step, and quantify the improvements.
Some compilers can also embed statements in advanced languages into assembly code as annotations. If your compiler provides

Feature, you can leave the advanced language code as the assembly code.

26.7 The more things change, the more they stay the more the same becomes, the less things it will change.
Code adjustment inevitably pays complexity, readability, simplicity, and maintainability for the good desire for performance improvement

. Since the performance needs to be re-evaluated after each adjustment, the code adjustment also introduces a huge amount of management and maintenance overhead.

Key Points
1. the optimization results vary greatly in different languages, compilers, and environments. If you do not measure each optimization, you will not

Method to Determine whether optimization helps or damages the program.
2. The first optimization is usually not the best. Even if you find that the results are good, do not stop expanding the pace of the results.
3. Code adjustment is a bit similar to nuclear power, controversial, and even impulsive. Some people think that code adjustment damages the code

Readability and maintainability, they will definitely discard it. Others think that as long as there is proper security protection, code adjustment will

Is beneficial. If you decide to use the adjustment method described in this chapter, be sure to proceed with caution.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.