How to Compile High-Quality VB Code

Source: Internet
Author: User
For details about how to Compile High-Quality VB code-Linux general technology-Linux programming and kernel information, see the following. Introduction:

This article describes how to improve the efficiency of VB code execution through some technical means. These methods can be divided into two major parts: encoding technology and compilation optimization technology. The coding technology introduces how to improve code execution speed and reduce system resources consumed by code by using efficient data types, reducing external references, and other programming methods. This article describes how to use the compilation options provided by VB to optimize the final executable files generated during compilation.

Preface

What is an efficient software? An efficient software should not only run faster than software that implements the same function, but also consume less system resources. This article brings together some experience accumulated by the author when using VB for software development, and demonstrates how to write efficient VB code through some simple examples. This includes some techniques that may be very helpful to VB programmers. Let me know a few concepts before we start.

Let code shape once: Many programmers I have come into contact with prefer to write code based on functional requirements and then optimize the code. Finally, they found that they had to re-write the code for the purpose of optimization. Therefore, we recommend that you consider optimization before writing code.

Grasp the relationship between the optimization result and the work that needs to be spent: Usually when a piece of code is completed, you need to check and modify it. When checking the code, you may find that the code efficiency in some loops can be further improved. In this case, many programmers pursuing perfection may immediately modify the code. It is recommended that you modify the code to shorten the running time of the program by one second. If the performance can only be improved by 10 ms, no changes are made. This is because rewriting a piece of code will certainly introduce new errors, and debugging new code will certainly take some time. Programmers should find a balance between the software performance and the workload required for software development, and 10 milliseconds is also an unrecognized difference for users.

Use the object-oriented method whenever possible. The mechanism provided by VB does not fully support object-oriented design and coding, but VB provides simple classes. Most people think that using objects will reduce code efficiency. I personally have some different opinions on this point. The efficiency of Code cannot be simply from the perspective of running speed. The resources occupied by software are also one of the factors to consider. The use of classes can help you improve the performance of the software as a whole, which will be detailed in the following examples.

When writing VB code, I hope you can use the above points as the guiding principles for your coding. I divided the article into two parts: How to Improve the code running speed and compilation optimization.

How to Improve code running speed

The following methods can help you improve the code running speed:

1. Use Integer and Long integers)

The easiest way to speed up code execution is to use the correct data type. Maybe you don't believe it, but choosing the correct data type can greatly improve the Code performance. In most cases, programmers can replace Single, Double, and Currency variables with Integer or Long variables, because VB can process Integer and Long much better than other data types.

In most cases, programmers choose to use Single or Double because they can save decimals. However, decimals can also be stored in Integer-type variables. For example, if the program has three decimal places, you only need to divide the value stored in the Integer variable by 1000 to get the result. Based on my experience, after using Integer and Long to replace Single, Double, and Currency, the code running speed can be increased by nearly 10 times.

2. Avoid using variants

For a VB programmer, this is nothing more obvious. Variables of the variant type need 16 bytes to store data, while an Integer only needs 2 bytes. Generally, the purpose of Variant Types is to reduce the workload and amount of code for the design, and some programmers can use it easily. However, if a software is strictly designed and encoded according to the specification, the variant type can be avoided.

Here, we will mention that the same problem exists for Object objects. See the following code:

Dim FSO
Set FSO = New Scripting. FileSystemObject

Or

Dim FSO as object
Set FSO = New Scripting. FileSystemObject

The above Code does not specify the data type during the declaration, which will waste the memory and CPU time when assigning values. The correct code should be as follows:

Dim FSO as New FileSystemObject

3. Avoid using attributes whenever possible

In normal code, the most common inefficient code is to repeatedly use properties when variables are available, especially in loops. You must know that the speed of the access variable is about 20 times the speed of the access attribute. The following code is used by many programmers in the program:

Dim intCon as Integer
For intCon = 0 to Ubound (SomVar ())
Text1.Text = Text1.Text & vbcrlf & SomeVar (intCon)
Next intCon

The following code is executed 20 times faster than the above Code.

Dim intCon as Integer
Dim sOutput as String
For intCon = 0 to Ubound (SomeVar ())
SOutput = sOutput & vbCrlf &
SomeVar (intCon)
Next
Text1.Text = sOutput

4. Try to use arrays to avoid using collections.

Unless you must use collections, you should try to use arrays. According to tests, the array access speed can reach 100 times of the set. This number sounds a little shocking, but if you consider a set as an object, you will understand why the difference is so big.

5. Expand a small loop body

During encoding, this situation may occur: a loop body only loops 2 to 3 times, and the loop body consists of several lines of code. In this case, you can expand the loop. The reason is that the cycle consumes additional CPU time. However, if the loop is complex, you do not need to do so.

6. Avoid using short functions.

Similar to using a small loop body, it is not economical to call a function with only a few lines of code. It may take longer to call a function than to execute the code in the function. In this case, you can copy the code in the function to the original place where the function is called.

7. Reduce references to child objects

In VB, objects are referenced by using. For example:

Form1.Text1. Text

In the preceding example, the program references two objects: Form1 and Text1. Using this method is inefficient. But unfortunately, there is no way to avoid it. The only thing a programmer can do is to use With or save the sub-object (Text1) With another object ).

'Use
With frmMain. Text1
. Text = "Learn VB"
. Alignment = 0
. Tag = "Its my life"
. BackColor = vbBlack
. ForeColor = vbWhite
End

Or

'Use another object to save the sub-Object
Dim txtTextBox as TextBox
Set txtTextBox = frmMain. Text1
TxtTextBox. Text = "Learn VB"
TxtTextBox. Alignment = 0
TxtTextBox. Tag = "Its my life"
TxtTextBox. BackColor = vbBlack
TxtTextBox. ForeColor = vbWhite

Note: the method mentioned above only applies to operations on the sub-objects of an object. The following code is incorrect:

With Text1
. Text = "Learn VB"
. Alignment = 0
. Tag = "Its my life"
. BackColor = vbBlack
. ForeColor = vbWhite
End

Unfortunately, we can often find code similar to the above in actual code. This only slows down code execution. The reason is that the With block will form a branch after compilation, which will add additional processing work.

8. Check whether the string is empty.

Most programmers use the following method when checking whether the string is null:

If Text1.Text = "" then
'Execute the operation
End if

Unfortunately, comparing strings requires even greater processing capacity than reading attributes. Therefore, we recommend that you use the following methods:

If Len (Text1.Text) = 0 then
'Execute the operation
End if

9. Remove the variable name after the Next keyword

Adding a variable name after the Next keyword will lead to a reduction in code efficiency. I don't know why, but it's just an experience. However, I think few programmers will be able to draw the cards in this way. After all, most programmers cherish words like gold.

'Error code
For iCount = 1 to 10
'Execute the operation
Next iCount
'Correct code
For iCount = 1 to 10
'Execute the operation
Next

10. Use arrays instead of multiple variables.

When you have multiple variables that store similar data, consider replacing them with an array. In VB, arrays are one of the most efficient data structures.

11. Use Dynamic Arrays instead of static Arrays

Using Dynamic Arrays does not significantly affect the code execution speed, but in some cases it can save a lot of resources.

12. Destroy objects

No matter what software you write, programmers need to consider releasing the memory space occupied by the software after the user decides to terminate the software operation. Unfortunately, many programmers do not seem very concerned about this. The correct method is to destroy the objects used in the program before exiting the program. For example:

Dim FSO as New FileSystemObject
'Execute the operation
'Destroy object
Set FSO = Nothing
You can unmount the form:
Unload frmMain

Or

Set frmMain = Nothing

13. Variable Length and fixed length string

Technically speaking, compared with variable-length strings, fixed-length strings require less processing time and space. However, the disadvantage of fixed-length strings is that in many cases, you need to call the Trim function to remove the null characters at the end of the string, which reduces the code efficiency. So unless the length of the string does not change, the variable-length string is used.

14. Use class modules instead of ActiveX Controls

Unless ActiveX controls involve user interfaces, use lightweight objects such as classes whenever possible. There is a big difference in efficiency between the two.

15. Use internal objects

When ActiveX controls and DLL are involved, many programmers prefer to compile them and then add them to the project. I suggest you do not do this because connecting from VB to an external object requires a lot of CPU processing power. Every time you call a method or access a property, a large amount of system resources are wasted. If you have ActiveX controls or DLL source code, use them as private objects of the project.

16. Reduce the number of modules

Some people like to save common functions in the module, and I agree with this. But writing only 20 or 30 lines of code in a module is a bit ridiculous. If you do not need a module, try not to use it. This is because VB loads the module into the memory only when the function or variable in the module is called. When the VB Application exits, the modules will be detached from the memory. If there is only one module in the code, VB only loads the code once, improving the code efficiency. If there are multiple modules in the code, VB performs multiple loading operations, reducing the code efficiency.

17. Use an array of Objects

When designing a user interface, programmers should try to use an array of objects for controls of the same type. You can do an experiment: Add 100 pictureboxes In the window. Each PictureBox has a different name and runs the program. Then create a new project and add 100 pictureboxes in the window. However, this time, you can use the object array and run the program to notice the difference in loading time between the two programs.

18. Use the Move Method

When changing the object location, some programmers prefer to use the Width, Height, Top, and Left attributes. For example:

Image1.Width = 100
Image1.Height = 100
Image1.Top = 0
Image1.Left = 0

In fact, this is very inefficient because the program modifies four attributes and the window will be repainted after each modification. The correct method is to use the Move method:

Image1.Move 0, 0, 100,100

19. Reduce image usage

Images occupy a large amount of memory, and processing images also consumes a lot of CPU resources. In software, if possible, you can consider using the background color to replace the image-of course, this is only from the technical perspective.

20. Use ActiveX DLL instead of ActiveX Control

If the ActiveX object you designed does not involve the user interface, use ActiveX DLL.

Compilation Optimization

Many of the VB programmers I have seen have never used compilation options, nor have they tried to figure out the differences between different options. Next let's take a look at the specific meanings of each option.

1. P-code (pseudo code) and Local Code

You can choose to compile the software into P-code or local code. The default option is the local code. So what is P-code and local code?
P-code: When executing code in VB, VB first compiles the code into P-code, and then explains the compiled P-code. In the compiling environment, this code is faster than the local code. After P-code is selected, VB puts the pseudo code into an EXE file during compilation.

Local Code: the local code is an option launched after VB6. After being compiled into an EXE file, the local code is executed faster than the P-code. After selecting the local code, VB uses the machine command to generate the EXE file during compilation.

When using the local code for compilation, I found that sometimes some inexplicable errors will be introduced. In the compilation environment, my code is fully correctly executed, but the EXE file generated with the native code option cannot be correctly executed. This usually happens when the window is unmounted or a print window is displayed. I solved this problem by adding the DoEvent statement to the code. Of course, there is very little chance of such a situation. Maybe some VB programmers have never met it, but it does exist.

There are several options in the local code:

A) code Speed Optimization: This option can compile execution files that are faster, but the execution files are relatively large. Recommended

B) Code Size Optimization: This option can compile a relatively small execution file, but it is not recommended at the cost of speed.

C) No optimization: This option only converts the P-code to the local code without any optimization. It can be used when debugging code.

D) Optimization for Pentium Pro: although this option is not the default option in the local code, I usually use this option. The executable programs compiled by this option can run faster on the Pentium Pro and Pentium 2 and later machines, but a little slower on older machines. Considering that Pentium 2 is outdated, we recommend that you use this option.

E) generate symbolic debugging information: This item generates some debugging information during the compilation process, so that you can use Visual C ++ tools to debug the compiled code. Using this token will generate a token file that records the Flag Information in the executable file. This option is helpful when the program has an API function or DLL call.

2. Advanced Optimization

The settings in advanced optimization can help you increase the speed of the software, but sometimes some errors are introduced. Therefore, I suggest you use them with caution. If the Code contains a large cyclic body or complex mathematical operations, selecting some items in advanced optimization greatly improves the code performance. If you use the advanced optimization function, we recommend that you strictly test the compiled files.

A) Assume that there is no alias: it can improve the efficiency of code execution in the loop body. However, if the variable value is changed through the reference of the variable, for example, calling a method, as a method parameter, if the value of a variable is changed in the method, an error is thrown. It may be a returned result error or a serious error that causes program interruption.

B) cancel the array binding check, cancel the integer overflow check, and cancel the floating point error check: If errors are found during the program running, the error handling code will handle these errors. However, if you cancel these checks, the program cannot handle the error. You can use these options only when you are sure that the above errors will not appear in your code. They will greatly improve the performance of the software.

C) float operations that are not supported: select this option to allow compiled programs to process float operations more quickly. Its only drawback is that comparing two floating point numbers may lead to incorrect results.

D) cancel the Pentium FDIV security check: This option is intended for some old Pentium chip settings, and now it seems outdated.

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.