Introduction: This article describes how to improve the performance efficiency of VB code through some technical means. These means can be divided into two large parts: coding technology and compilation optimization techniques. In the encoding technique, how to improve the code execution speed and reduce the system resources of code consumption by reducing external references such as external reference. In the compilation optimization technology, the compilation options that correctly use VB are optimized to optimize the executable generated by the last generated time generated.
Foreword
What is an efficient software? A efficient software should not only run faster than the software that achieve the same function, but also consume fewer system resources. This article brings together some of the authors who have accumulated in software development when using VB, through some simple examples to show you how to write efficient VB code. It contains some techniques that may be very helpful to VB programmers. Before starting, let me first let me know a few concepts.
Let code once: among the programmers I have touched, there are many people like to write the code according to the functional needs, and then optimize the code on this basis. Finally, we have to re-write the code again in order to achieve optimization. So I suggest that you need to consider optimization before writing code.
Grasp the results of optimization and the relationship between work needs to be taken: Usually, you need to check and modify it. In the process of checking the code, maybe you will find that the code efficiency in some cycles can also be further improved. In this case, many of the pursuit of perfect programmers may immediately modify the code. My suggestion is that if this code will make the program's runtime shorten, you can modify it. If you can only bring 10 millisecond performance improvements, don't make any changes. This is because rewriting a code will definitely introduce new errors, and debugging new code will definitely spend a certain time. Programmers should find a balance between software performance and development software, and 10 milliseconds are also a difference that cannot be realized for users.
Try to use it when you need to use object-oriented methods; VB provides the mechanism that does not fully support object-oriented design and encoding, but VB provides a simple class. Most people think that the use of objects will result in low efficiency of the code. For this point I personally have some different opinions; the efficiency of the exam code cannot be purely from the perspective of running speed, the resources occupied by the software also need to consider the factors. Use classes to help you improve your software as a whole, which will be described in detail in later examples.
When you write VB code, I hope you can use the above point as the principle of guiding your coding. I divide the article into two parts: how to improve the running speed and compilation optimization of the code.
How to improve the running speed of the code
The following methods can help you improve your code's running speed:
1. Using an integer and long integer (long)
Improve the easiest way to run the code run is too used to use the correct data type. Maybe you don't believe, but correctly select the data type can greatly enhance the performance of the code. In most cases, the programmer can replace the variable of the SINGLE, DOUBLE and CURRENCY types with the Integer or LONG type variable because VB processes Integer and Long far more than processing other data types.
In most cases, programmers choose to use Single or Double because they can save decimals. However, decimal can also be saved in the Integer type variable. For example, there are about three decimals in the program, then only the values saved in the Integer variable can be obtained in 1000. According to my experience, after using Integer and long, after SINGLE, DOUBLE and CURRENCY, the running speed of the code can be increased by nearly 10 times.
2. Avoid using variants
For a VB programmer, this is a matter of obvious things. Variable type variables require 16 bytes of space to save data, and an integer requires only 2 bytes. Usually the purpose of the variant type is to reduce the amount of design and code, and some programmers use it. But if a software has been strictly designed and coded in accordance with the specification, it can avoid the use of variant types. Here, there is also the same problem for the Object object. Please see the following code:
DIM FSO SET FSO = New scripting.filesystemObject
or
DIM FSO As ObjectSet Fso = New Scripting.FileSystemObject
The above code is wasting the memory and CPU time when the value is not specified during the declaration. The correct code should be like this:
DIM FSO AS New FileSystemObject3. Try to avoid using properties
In the usual code, the most common relatively inefficient code is to use the attribute (Property), especially in the cycle. To know that the speed of access variable is about 20 times the speed of access attribute. The following code is that many programmers will use in the program:
DIM INTCON AS INTEGERFOR INTCON = 0 to Ubound (Somvar ()) text1.text = text1.text & vbcrlf & somevar (intcon) Next Intcon
The execution speed of the code below is 20 times the above code.
DIM INTCON AS INTEGERDIM SOUTPUT AS STRINGFOR INTCON = 0 to Ubound (SomeVar ()) SOUTPUT = SOUTPUT & VBCRLF & Somevar (intcon) NextText1.text = SOUTPUT
4. Try to use arrays to avoid using collection
Unless you have to use a collection, you should try to use an array. According to the test, the access speed of the array can reach 100 times the collection. This figure sounds a bit awkward, but if you consider the collection is an object, you will understand why the difference will be so big.
5. Expand small cyclic body
At the time of encoding, it is possible to encounter this situation: one cycle will only circulate 2 to 3 times, and the cyclic body consists of several lines of code. In this case, you can expand the loop. The reason is that the loop will take up additional CPU time. But if the loop is more complicated, you don't have to do this.
6. Avoid using a short function
Similarly to using small cycles, calling only a few lines of code is also an economical - the time spent in calling functions may take longer than the code in the execution function. In this case, you can copy the code in the function to the place where the function is called.
7. Reduce the reference to child objects
In VB, by use. Reference to the object. E.g:
Form1.text1.text
In the above example, the program references two objects: Form1 and Text1. This method is low. But unfortunately, there is no way to avoid it. The only programmer can do it is useless or will hold the sub-object with another object.
'Use withwith frmmain.text1.text = "learn vb" .alignment = 0.tag = "it" .BackColor = vbblack.forecolor = vbwhiteend with or
'Save the child object with another Object Dim txtTextBox as TextBoxSet txtTextBox = frmMain.Text1TxtTextBox.Text = "Learn VB" TxtTextBox.Alignment = 0TxtTextBox.Tag = "Its my life" TxtTextBox.BackColor = vbBlackTxtTextBox.ForeColor = vbWhite
Note that the method mentioned above is only applicable to the time when the child objects need to be operated, the following code is incorrect:
With text1.text = "learn vb" .alignment = 0.tag = "its my life" .BackColor = vbbblack.forecolor = vbwhiteend with
Unfortunately, we can often find similar to the above code in the actual code. This will only make the code's execution speed slower. The reason is that the WITH block is compiled and a branch will increase the additional processing.
8. Check if the string is empty
Most programmers use the following methods when checking whether the string is empty:
If text1.text = "" ""
Unfortunately, the amount of handles required for strings is even more than reading attributes. So I suggest that you use the following methods:
If Len (Text1.Text) = 0 THEN 'Performs Operation End IF
9. Remove the variable name after the next keyword
After the NEXT keyword, add the variable name caused the efficiency of the code to decrease. I don't know why, just an experience. However, I think very few programmers will draw such a snake, after all, most of the programmers are all people who are like gold.
'Wrong code for iCount = 1 to 10' execution operation Next iCount 'correct code for iCount = 1 to 10' execution operation Next
10. Use arrays instead of multiple variables
When you have multiple variables that save similar data, you can consider replacing them with one array. In VB, arrays are one of the most efficient data structures.
11. Use dynamic arrays instead of static arrays
Using the dynamic array's execution speed of the code does not have too much impact, but in some cases a large amount of resources can be saved.
12. Destroy the object
No matter what software written, the programmer needs to consider the memory space occupied by the user decided to terminate the software after running. But unfortunately, many programmers seem to be very concerned about this. The correct approach is to destroy the objects used in the program before exiting the program. E.g:
DIM FSO AS New FileSystemObject 'Performs action' Destruction Object SET FSO = Nothing For the form, you can uninstall: unload frmmain
or
Set frmmain = Nothing
13. Growth and fixed length strings
Technically, the fixed length string requires less processing time and space than the bell string. But the disadvantage of the fixed length string is that in many cases, you need to call the Trim function to remove the empty character of the string, which will reduce the code efficiency. Therefore, unless the length of the string does not change, otherwise it is still used. 14. Use class modules instead of ActiveX controls
Unless the ActiveX control involves the user interface, minimize the use of lightweight objects, such as classes. The efficiency between the two is very different.
15. Use internal objects
Many programmers like to compile them with ActiveX controls and DLLs, and then join the project. I suggest you do not do this because it takes a lot of CPU processing capabilities from VB to an external object. Whenever you call methods or access properties, you will waste a lot of system resources. If you have an ActiveX control or DLL source code, use them as a private object of the project.
16. Reduce the number of modules
Some people like to save common functions in the module and agree with this. But in a module, I only write a two-30 line code. If you are not a very needed module, try not to use it. The reason is because only the modules are loaded into memory only when the functions or variables in the module are called; these modules are uninstalled from memory when the VB application exits. If there is only one module in the code, VB will only load operation, so the efficiency of the code is improved; if there are multiple modules in the code, VB will perform multiple load operations, the efficiency of the code will decrease.
17. Use an array of objects
When designing the user interface, for the same type of control, programmers should try to use an object array. You can do an experiment: add 100 Picturebox on the window, each PictureBox has a different name, running the program. Then create a new project, and add 100 Picturebox on the window, but this time you use an object array, run the program, you can notice the difference in two programs loaded.
18. Using the MOVE method
When changing the location of the object, some programmers like to use Width, HEIGHT, TOP, and LEFT properties. E.g:
Image1.width = 100Image1.height = 100Image1.top = 0image1.left = 0
In fact, this is very efficient, because the program modifies four attributes, and after each modification, the window will be reoccup. The correct approach is to use the MOVE method:
Image1.move 0,0,100,100
19. Reduce the use of pictures
The picture will take up a large amount of memory, and the picture also needs to take up a lot of CPU resources. In the software, if possible, consider replacing the picture with a background color - of course, this is just from the perspective of the technician.
20. Using ActiveX DLL instead of ActiveX control
If the ActiveX object you designed does not involve the user interface, use the ActiveX DLL.
Compiling Optimization I have seen many VB programmers never use compilation options, nor did they try to figure out the difference between the various options. Let us take a look at the specific meaning of each option.
1. P-code (pseudo code) and native code
You can choose to compile the software as a P-code or this machine code. The default option is this unit code. What is P-code and this unit?
P-code: When executed in VB, VB first is to compile the code as a P-code, and then explain the P-code to perform compilation. In the compilation environment, use this code to be faster than this code. After selecting the P-code, it is compiled when VB puts the pseudo code in an EXE file. This machine code: The native code is the option to be launched later in VB6. When compiled into an EXE file, the execution speed of the unit is faster than the P-code. After selecting the unit code, the VB is compiled using the machine instruction to generate an EXE file.
When compiling using this unit code, I found that sometimes it will introduce some inexplicable errors. My code is fully implemented in the compilation environment, but the EXE file generated with this unit code option cannot be executed correctly. Usually, this happens when the uninstall window or pops up the print window. I solved this problem by joining the DOEVENT statement in the code. Of course, this situation has very little chance, maybe some VB programmers have never encountered, but it does exist.
There are also several options in this unit:
a) Code speed optimization: This option can compile speed of fast execution files, but the execution file is relatively large. Recommended Use
b) Code Size Optimization: This option can compile a relatively small execution file, but is not recommended at the expense of speed, not recommended.
c) No optimization: This option is just converting P-code into native code and does not do any optimization. You can use it when debugging the code.
d) Optimization for Pentium PRO: Although this item is not the default option in this unit, I usually use this option. The option compiled executable can run faster on the machine PRO and Pentium 2 or more, and more slower in the older machine. Considering that now use Pentium 2, it is a ruin, so I recommend you to use this option.
e) Generate symbolization debug information: This item generates some debugging information during the compilation process, allowing users to use the Visual C tool to debug compilation code. Use this option to generate a .pdf file that records the flag information in the executable file. This option is still more help when the program has an API function or DLL call.
2. Advanced optimization
The settings in advanced optimization can help you improve the speed of the software, but sometimes it will introduce some errors, so I suggest that you use them carefully. If there is a relatively large cyclic body or a complex mathematical operation in your code, some items in the premium optimization will greatly enhance the performance of the code. If you use advanced optimization, I suggest you strictly test the compiled file.
a) Assume that there is no alias: can improve the execution efficiency of the code in the circulation body, but if the variable is changed by the reference value by the variable, for example, a method of calling a method, the variable is used as a parameter of the method, the variable is changed in the method. If the value is, it will trigger an error. It may be just the result of the result of returning, or it may be a serious error that causes the program interrupt operation.
b) Cancel the array binding check, cancel the integer overflow check and cancel floating point error check: When the program is running, if an error is discovered through these checks, the error handling code will handle these errors. However, if these checks have been canceled, the error program cannot be processed. You can use these options only when you make sure that you don't have the above errors in your code. They will enhance the performance of the software.
c) Allow the floating point operations that are incorporated: Select this option to be compiled programs to process floating point operations faster. The only disadvantage is that it may cause incorrect results when comparing two floating point numbers.
d) Cancel the Pentium FDIV security check: This option is for some old Pentium chip settings, it seems that it has been out.