Delphi code optimization

Source: Internet
Author: User

Author/Duyun reposted fromProgramMember magazine issue 4

Local variable

Unlike C, Delphi does not have a register-like indicator and cannot explicitly define a register variable, because the Delphi compiler has made this step intelligent. Some local variables are automatically used as register variables. Of course, Delphi has its own internal standards. Generally, many referenced variables can always be optimized. Global variables do not have this benefit. Of course, there are also exceptions. An array with simple variables as elements can save a register as a global variable, "stack variables" such as strings, dynamic arrays, and objects do not necessarily localize them. (They are called "stack variables" because, as local variables, they only store a pointer in the stack and point to the storage zone allocated in the heap. Therefore, additional portals and exits are required.CodeBorland official explanation for this is that heap is faster than stack .)

Local Process

It is also a unique syntax of Delphi. However, calling a local process brings about additional stack operations so that the variables in the parent process can be accessed in a local process. Therefore, it is necessary to remove the local process and then use parameters to pass the required variables.

Process Parameters

In Delphi, the default call convention is register. In this mode, eax, ECx, and EDX can be used to pass parameters. Therefore, there are generally no more than three parameters in the process. In object type methods, we recommend that you set no more than two parameters because of the implicit self pointer.

Pointer variable

Pointers are very useful. They are discarded in Java and re-picked in C. In Delphi, the pointer is 4 bytes in size and can also be register. Sometimes we can "imply" that the compiler does this by using the with clause, for example:
With somestructure. somevar [I] Do // some variables are classes or structures
Begin
...
End;
In this way, somestructure. somevar [I], which will not be optimized, will be registered.

Array

Since PII has greatly improved its dynamic array and multiplication capabilities, linked lists are rarely used in actual programming except in textbooks, arrays are indeed much faster than traditional linked lists.
In Delphi, the array type has a static array (var a: array [0 .. 9] of byte), dynamic array (var a: array of byte), pointer array (pointer to static array), and open array (for parameter transfer only ). Static arrays and pointer arrays have the advantage of fast speed, and dynamic arrays have the advantage of variable size. The trade-off is that the defined dynamic array is converted to a pointer when necessary.
It is worth noting that dynamic arrays without const or var will be passed as form parameters, changing dynamic arrays with const does not mean that you cannot modify the elements in the array (do not believe that you add a [1]: = 0 in the above example; the compiler will not report an error ). In the preceding example, length (a) is used because high calls length.

Process Control

For structured programs, break, continue, and exit are not widely promoted, but the code they produce is the most concise, so they still have a place in programming.
Delphi introduced the concept of exception, which should be said to be a major improvement of Object Pascal. However, exception capture is based on the addition of additional code. A try block is nested out of a few codes or exception capture is used inside the loop, which does not affect the efficiency. In addition, it is not a good habit to discard exceptions without handling them.

Forced type conversion

Many people use absolute for type conversion, but this will prevent this variable from becoming a register variable. Therefore, using type conversion in the process is a better choice.

Enumeration, Set

For the set type, the include and exclude ratio S: = S + [a] is faster when you increase or decrease a single element. This is not required.
In addition, you can use the {$ Zn} indicator to define the size of the enumeration type. defining it as four bytes of {$ Z4} may be faster.

New problems brought about by Pentium II

The most unusual feature of PII is its ability to "exceed the limit, multi-channel, and unordered execution. "Multi-Channel" means that the CPU has three loading channels (two of which can only load simple commands) five execution channels (one for integer operation, one for integer and floating-point operations, one for address operation, and two for data access) and three unload channels; "out-of-order execution" allows commands that do not affect each other to be executed simultaneously within the same clock cycle and in different channels. The impact on code execution is that some commands need to execute one or two clock cycles (such as continuous floating point operations), some do not require additional execution cycles because of parallelism (for example, after calculation ). The above is just an overview. For more details, refer to the dedicated Pentium optimization guide and Intel documentation.

CPU View

The delphi32 ide has a CPU view (you can enable it by modifying the registry key in delphi2 and 3). When debugging, check the corresponding Assembly source code to understand the code optimization, even accurate calculation of the required clock cycle (if you have enough) is quite effective.

Loop statement

Delphi has its own unique and effective method for compiling loop statements, and it works well in most cases, but sometimes it also needs some other tricks, for example, use a while structure that is closer to the "assembly nature" in a small loop. In addition, for compact loops that open them into non-circular code, it seems better to adapt to the tendency of branch prediction under Pii.
Example of an optimization cycle:
For I: = 1 to 40 do
Begin
If I = 20 then a [I]: = A [I] + 20 else a [I]: = A [I] + 10;
End
Rewrite:
For I: = 1 to 19 do a [I]: = A [I] + 10;
A [20]: = A [20] + 20;
For I: = 21 to 40 do a [I]: = A [I] + 10;
Increases the amount of code, but reduces the number of judgments. Reducing the cycle condition judgment is also the key to growth.

Case statement

When there are many sub-Boundaries of case statements, you may want to divide them into several parts and set another layer of case.
When one or two items are frequently used in the subfield of a case statement, you can place them before the case and use if to judge them.

Fill and move memory

When filling and moving a large amount of memory, it is best to write the Assembly by yourself, with 32-bit instructions. However, when using commands such as movsd and stosd, it is easy to encounter a problem: the data address or size (especially the latter) does not have dual-word alignment. What should I do? The answer is that there is an empty sub-drill. Most data is always aligned by double words when being distributed. For example, only DWORD alignment is considered. Of course, we recommend that you exercise caution in view of the potential risks brought by this practice to bugs.

Interfaces and Virtual Methods

Like java, Object Pascal does not support multiple inheritance, but can be implemented using interfaces. But in Delphi, interface means double pointer.
To call a virtual method, you need to get the VMT pointer through the object pointer, and then obtain the method pointer from VMT. Therefore, you can use a work und to implement it if necessary.

Code alignment

Code alignment has the disadvantage of increasing the code size, but the benefits of its speed improvement make this sacrifice worthwhile, so it is generally recommended to open it.

Code style

Pascal is a beautiful language (compared with C ++, It is a concise language-I do not mean to be honest here ). Personally, I am unwilling to undermine this kind of beauty for optimization. Fortunately, Delphi won't make me feel embarrassed. Rather, chaotic code will bring problems. Therefore, it is necessary to maintain a good code style.

Trust the Compiler

Borland has the best compiler in the world (maybe better in your mind), which is not only fast, but also top-notch in compilation optimization. Therefore, in most cases, the natural code can achieve high efficiency. You don't have to worry about every piece of code, as long as the key part is fast enough.

Code timing

Timing is a very effective method in code optimization, and there are many software available in this area. Although it's not necessary to take a question, as some magazines have said, xxxmark. However, it is a great sense of accomplishment to quantify the actual improvement of your code efficiency.

Conclusion

People tend to have a wonderful set of rules to deal with all the situations. UnfortunatelyArticleInvalid, same for code optimization. The most effective optimization is not too muchAlgorithm. Therefore, to allow programmers to keep an open mind and keep learning and practice is the best way to succeed.

 

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.