What is an efficient software? An efficient software should not only run faster than software that performs the same function, but should also consume fewer system resources. This article brings together some of the experience accumulated by the author when using VB for software development, and uses 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 I begin, let me clarify a few concepts.
Let the code take shape at once: Among the programmers I have come into contact with, many people like to write the code first according to the functional requirements, and then optimize the code on this basis. In the end, they found that in order to achieve optimization, they had to rewrite the code. So I suggest you consider optimization issues before writing code.
Understand the relationship between the results of optimization and the work required: usually when a piece of code is completed, you need to inspect and modify it. In the process of inspecting the code, you may find that the code efficiency in some loops can be further improved. In this case, many programmers who pursue perfection may modify the code immediately. My suggestion is that if changing this code will shorten the running time of the program by one second, you can change it. If it can only bring about a 10 millisecond performance improvement, no changes will be made. This is because rewriting a piece of code will inevitably introduce new errors, and debugging new code will definitely take you a certain amount of time. Programmers should find a balance between software performance and the amount of work required to develop the software, and 10 milliseconds is a difference that users cannot appreciate.
Try to use object-oriented methods when you need to use them; the mechanism provided by VB does not fully support object-oriented design and coding, but VB provides simple classes. Most people believe that using objects will result in less efficient code. I personally have some different opinions on this point; the efficiency of code cannot be evaluated purely from the perspective of running speed. The resources occupied by the software are also one of the factors that need to be considered. Using classes can help you improve the overall performance of your software, which I will explain in detail in later examples.
When you write VB code, I hope you can use the above points as principles to guide your coding. I divided the article into two parts: how to improve the running speed of the code and compilation optimization.
How to make your code run faster
The following methods can help you improve the speed of your code:
1. Use integers (Integer) and long integers (Long)
The easiest way to make your code run faster is to use the right data types. You may not believe it, but choosing the correct data type can greatly improve the performance of your code. In most cases, programmers can replace Single, Double, and Currency type variables with Integer or Long type variables, because VB's ability to handle Integer and Long is much higher than that of other data types.
In most cases, the reason programmers choose to use Single or Double is because of their ability to save decimals. But decimals can also be stored in variables of type Integer. For example, if there are three decimal places agreed in the program, then you only need to divide the value stored in the Integer variable by 1000 to get the result. In my experience, code can run nearly 10 times faster by using Integer and Long instead of Single, Double, and Currency.
2. Avoid using variants
For a VB programmer, this is obvious. Variables of variant types require 16 bytes of space to store data, while an integer (Integer) only requires 2 bytes. Usually the purpose of using variant types is to reduce the design workload and the amount of code. Some programmers also use it to save trouble. But if a software is strictly designed and coded according to specifications, the use of variant types can be completely avoided.
By the way, the same problem also exists for Object objects. Please look at the code below:
mFSO
SetFSO=NewScripting.FileSystemObject
or
DimFSOasobject
SetFSO=NewScripting.FileSystemObject
Since the above code does not specify the data type when declaring, memory and CPU time will be wasted during assignment. The correct code should look like this:
DimFSOasNewFileSystemObject
3. Try to avoid using attributes
In daily code, the most common inefficient code is to repeatedly use properties (Property) when variables can be used, especially in loops. You must know that the speed of accessing variables is about 20 times that of accessing attributes. The following code is used by many programmers in their programs:
DimintConasInteger
ForintCon=0toUbound(SomVar())
Text1.Text=Text1.Text&vbcrlf&SomeVar(intCon)
NextintCon
The code below executes 20 times faster than the code above.
DimintConasInteger
DimsOutputasString
ForintCon=0toUbound(SomeVar())
sOutput=sOutput&vbCrlf&
SomeVar(intCon)
Next
Text1.Text=sOutput
4. Try to use arrays and avoid using sets
Unless you must use a collection, you should always use an array. According to tests, the access speed of arrays can reach 100 times that of collections. This number sounds a bit shocking, but if you consider that a collection is an object, you'll understand why the difference is so large.
5. Expand the small loop body
When coding, you may encounter this situation: a loop body will only loop 2 or 3 times, and the loop body consists of several lines of code. In this case, you can unroll the loop. The reason is that the loop takes up extra CPU time. But if the loop is more complex, you don't need to do this.
6. Avoid using very short functions
As with using small loops, it is uneconomical to call a function with only a few lines of code - calling the function may take longer than executing the code in the function. In this case, you can copy the code in the function to the place where the function was originally called.
7. Reduce references to sub-objects
In VB, object references are implemented using . For example:
Form1.Text1.Text
In the above example, the program references two objects: Form1 and Text1. Quoting using this method is inefficient. But unfortunately, there is no way to avoid it. The only thing the programmer can do is to use With or save the child object (Text1) with another object.
Note: Use With
WithfrmMain.Text1
.Text="LearnVB"
.Alignment=0
.Tag="Itsmylife"
.BackColor=vbBlack
.ForeColor=vbWhite
EndWith
or
Note: Use another object to save the child object
DimtxtTextBoxasTextBox
SettxtTextBox=frmMain.Text1
TxtTextBox.Text="LearnVB"
TxtTextBox.Alignment=0
TxtTextBox.Tag="Itsmylife"
TxtTextBox.BackColor=vbBlack
TxtTextBox.ForeColor=vbWhite
Note that the method mentioned above is only applicable when you need to operate on sub-objects of an object. The following code is incorrect:
WithText1
.Text="LearnVB"
.Alignment=0
.Tag="Itsmylife"
.BackColor=vbBlack
.ForeColor=vbWhite
EndWith
Unfortunately, we can often find code similar to the above in actual code. Doing so will only make the code execute slower. The reason is that the With block will form a branch after compilation, which will add additional processing work.
8. Check if the string is empty
Most programmers use the following method when checking whether a string is empty:
IfText1.Text=""then
Note: perform operations
Endif
Unfortunately, doing string comparisons requires even more processing than reading properties. Therefore I suggest you use the following method:
IfLen(Text1.Text)=0then
Note: perform operations
Endif
9. Variable name after removing Next keyword
Adding the variable name after the Next keyword will cause the efficiency of the code to decrease. I don't know why this happens, it's just an experience. But I think very few programmers would go so far as to add superfluous information. After all, most programmers are people who cherish words like gold.
Comment: Wrong code
ForiCount=1to10
Note: perform operations
NextiCount
Note: Correct code
ForiCount=1to10
Note: perform operations
Next
10. Use arrays instead of multiple variables
When you have multiple variables that hold 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 will not have a big impact on the execution speed of the code, but in some cases it can save a lot of resources.
12. Destroy objects
No matter what kind of software is written, programmers need to consider releasing the memory space occupied by the software after the user decides to terminate the software. But unfortunately, many programmers don't seem to care much about this. The correct approach is to destroy the objects used in the program before exiting the program. For example:
DimFSOasNewFileSystemObject
Note: perform operations
Note: Destroy the object
SetFSO=Nothing
For forms, you can uninstall:
UnloadfrmMain
or
SetfrmMain=Nothing
13. Variable-length and fixed-length strings
Technically speaking, fixed-length strings require less processing time and space than variable-length strings. However, the disadvantage of fixed-length strings is that in many cases, you need to call the Trim function to remove the null character at the end of the string, which will reduce code efficiency. So unless the length of the string will not change, use variable-length strings.
14. Use class modules instead of ActiveX controls
Unless ActiveX controls involve user interfaces, try to use lightweight objects such as classes. There is a big difference in efficiency between the two.
15. Use internal objects
When it comes to using ActiveX controls and DLLs, many programmers like to compile them and then add them to the project. I would advise you not to do this because connecting to an external object from VB requires a lot of CPU processing power. Every time you call a method or access a property, you waste a lot of system resources. If you have the source code for an ActiveX control or DLL, make them private objects in the project.
16. Reduce the number of modules
Some people like to keep common functions in modules, and I agree with that. But writing only twenty or thirty lines of code in a module is a bit ridiculous. If you don't really need a module, try not to use it. The reason for this is because VB loads modules into memory only when functions or variables in the module are called; these modules are unloaded from memory when the VB application exits. If there is only one module in the code, VB will only perform one loading operation, so the efficiency of the code will be improved; conversely, if there are multiple modules in the code, VB will perform multiple loading operations, and the efficiency of the code will be reduced.
17. Use object arrays
When designing user interfaces, programmers should try to use object arrays for controls of the same type. You can do an experiment: add 100 PictureBoxes to the window, each with a different name, and run the program. Then create a new project, also add 100 PictureBoxes to the window, but this time use an object array, run the program, you can notice the difference in the loading time of the two programs.
18. Use the Move method
When changing the position of an object, some programmers like to use the Width, Height, Top and Left properties. 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 properties, and after each modification, the window will be redrawn. The correct approach is to use the Move method:
Image1.Move0,0,100,100
19. Reduce the use of images
Images will take up a lot of memory, and processing them also requires a lot of CPU resources. In software, if possible, consider using background colors instead of pictures - of course this is just a technical person's perspective on this issue.
20. Use ActiveXDLL instead of ActiveX controls
If the ActiveX object you are designing does not involve a user interface, use ActiveXDLL.
Compilation optimization
Many VB programmers I've met have never used compile options or tried to figure out the differences between the options. Let's take a look at the specific meaning of each option.
1.P-code (pseudocode) and native code
You can choose to compile the software to P-code or native code. The default option is native code. So what are P-code and native code?
P-code: When executing code in VB, VB first compiles the code into P-code, and then interprets and executes the compiled P-code. In a compiled environment, using this code is faster than native code. After selecting P-Code, VB puts the pseudocode into an EXE file when compiling.
Native code: Native code is an option introduced only after VB6. When compiled into an EXE file, native code executes faster than P-code. After selecting native code, VB uses machine instructions to generate an EXE file when compiling.
When compiling with native code, I find that sometimes inexplicable errors are introduced. My code is executed completely correctly in the compilation environment, but the EXE file generated with the native code option does not execute correctly. Usually this happens when a window is unloaded or a print window pops up. I solved this problem by adding a DoEvent statement to the code. Of course, the chance of this happening is very rare. Maybe some VB programmers have never encountered it, but it does exist.
There are also several options in native code:
a) Code speed optimization: This option can compile a faster executable file, but the executable file is larger. Recommended
b) Code size optimization: This option can compile a smaller executable file, but at the expense of speed, it is not recommended.
c) No optimization: This option only converts P-code into native code without any optimization. Can be used when debugging code.
d) Optimized for Pentium Pro: Although this option is not the default option in native code, I usually use this option. The executable program compiled with this option can run faster on PentiumPro and Pentium2 or above machines, but will be slightly slower on older machines. Considering that using Pentium2 is outdated now, it is recommended that everyone use this option.
e) Generate symbolic debugging information: This item generates some debugging information during the compilation process, allowing users to use tools such as Visual C++ to debug the compiled code. Using this option generates a .pdf file that records the flag information in the executable file. This option is helpful when the program has API functions or DLL calls.
2. Advanced optimization
The settings in Advanced Optimization can help you improve the speed of your software, but sometimes they can introduce bugs, so I recommend that you use them as carefully as possible. If there are relatively large loop bodies or complex mathematical operations in the code, selecting certain items in the advanced optimization will greatly improve the performance of the code. If you use advanced optimization features, I recommend rigorously testing the compiled files.
a) Assuming no alias: This can improve the execution efficiency of the code in the loop body, but if the variable value is changed through a variable reference, such as calling a method, the variable reference is used as a parameter of the method, and the variable's value is changed in the method. value, an error will be raised. It may just be that the returned result is wrong, or it may be a serious error that causes the program to interrupt.
b) Cancel array binding check, cancel integer overflow check and cancel floating point error check: When the program is running, if errors are found through these checks, the error handling code will handle these errors. But if these checks are cancelled, the program will not be able to handle an error. You should use these options only if you are sure that the above errors will not occur in your code. They will greatly improve the performance of the software.
c) Allow floating-point operations without rounding: Selecting this option allows the compiled program to process floating-point operations faster. Its only disadvantage is that it may lead to incorrect results when comparing two floating point numbers.
d) Cancel PentiumFDIV security check: This option is set for some old Pentium chips and now seems to be outdated