How to write high quality VB code

Source: Internet
Author: User
Tags array arrays data structures empty integer variables require requires

Objective

What is an efficient software? An efficient software should not only run faster than software that implements the same functionality, but it should also consume less system resources. This article brings together some of the experiences that the author has accumulated while using VB for software development, and shows you how to write efficient VB code with some simple examples. It contains some techniques that may be very helpful to VB programmers. Before I start, let me ching a few concepts.

Let the code take shape once: in the programmers I have contacted, many people like to write the code according to the functional requirements first, then optimize the code on this basis. Finally found that they had to rewrite the code again for the purpose of optimization. So I suggest you need to think about optimization before you write your code.

Grasp the relationship between the results of the optimization and the work that needs to be spent: usually when a piece of code is completed, you need to check and modify it. In the process of checking the code, you may find that the code efficiency in some loops can be further improved. In this case, many of the perfect programmers may immediately modify the code. My suggestion is that if you modify this code to shorten the program's running time by one second, you can modify it. If you can only bring performance improvements for 10 milliseconds, no changes are made. This is because rewriting a piece of code is bound to introduce new bugs, and debugging new code will certainly take you a certain amount of time. Programmers should find a balance between software performance and the amount of work that is needed to develop the software, and 10 milliseconds is an impossible difference for users.

Use it when you need to use object-oriented methods; VB provides a mechanism that does not fully support object-oriented design and coding, but VB provides a simple class. Most people think that using objects will result in less efficient code. I have a different opinion on this point; the efficiency of the code can not be purely from the point of view of running speed, the resources occupied by the software is also one of the factors to be considered. Using classes can help you improve the performance of your software as a whole, which I'll explain in a later example.

When you write VB code, I hope you can use the above points as a guideline to guide your coding. I divided the article into two parts: how to improve the speed of code and compile optimization.

How to improve the speed of your code

Here are some ways to help you increase your code's speed:

1. Using integers (integer) and long integers (long)

The easiest way to increase the speed of your code is to use the correct data type. You may not believe it, but choosing a data type correctly can greatly improve the performance of your code. In most cases, programmers can replace variables of type single,double and currency with integers or long variables, because the ability of VB to handle integers and long is much higher than dealing with several other data types.

In most cases, the reason programmers choose to use single or double is because they can hold decimals. But decimals can also be saved in variables of type integer. For example, there are three decimal places in the program, so you just need to divide the number stored in the integer variable by 1000 to get the result. In my experience, the code can run nearly 10 times times faster with integers and long instead of single,double and currency.

2. Avoid using variants

For a VB programmer, this is a more obvious thing. Variant type variables require 16 bytes of space to hold the data, while an integer (integer) requires only 2 bytes. The purpose of the variant type is usually to reduce the amount of work and code in the design, as well as to make it easier for the programmer to use it. However, if a software is strictly designed and coded in accordance with the specification, the variant type can be avoided entirely.

Incidentally, the same problem exists for object objects. Take a look at the following code:

Dim FSO
Set FSO = New Scripting.FileSystemObject

Or

Dim FSO As Object
Set FSO = New Scripting.FileSystemObject

The above code wastes memory and CPU time when assigning values because no data type is specified at the time of the Declaration. The correct code should look like the following:

Dim FSO as New FileSystemObject
3. Try to avoid using attributes

In normal code, the most common and inefficient code is to use attributes repeatedly, especially in loops, when variables can be used. To know the speed of the access variable is about 20 times times the speed of the Access property. 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 executes 20 times times faster than the code above.

Dim Intcon as Integer
Dim Soutput as String
For Intcon = 0 to Ubound (Somevar ())
Soutput = soutput & VbCrlf &
Somevar (Intcon)
Next
Text1.Text = Soutput

4. Use arrays as much as possible to avoid using collections

Unless you have to use a set (Collection), you should use arrays as much as possible. According to the test, the access speed of array can reach 100 times times of the collection. This number may sound shocking, but if you consider that a collection is an object, you will understand why the difference is so great.

5. Expand the small circulation body

When coding, it is possible that a loop body will only loop 2 to 3 times, and that the loop body consists of several lines of code. In this case, you can expand the loop. The reason is that the loop consumes extra CPU time. But if the loops are more complex, you don't have to do that.

6. Avoid using very short functions

As with a small loop body, a function that calls only a few lines of code is also not economical-the time it takes to invoke a 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 child objects

In VB, a reference to an object is implemented by using the. For example:

Form1.Text1.Text

In the example above, the program refers to two objects: Form1 and Text1. It is inefficient to use this method of reference. But unfortunately, there is no way to avoid it. The only thing a programmer can do is use with or save a child object (TEXT1) with another object.

' Use with
With Frmmain.text1
. Text = "Learn VB"
. Alignment = 0
. Tag = "Its I Life"
. BackColor = Vbblack
. ForeColor = Vbwhite
End With

Or

' Save child objects with another object
Dim Txttextbox as TextBox
Set Txttextbox = Frmmain.text1
Txttextbox.text = "Learn VB"
txttextbox.alignment = 0
Txttextbox.tag = "Its I Life"
Txttextbox.backcolor = Vbblack
Txttextbox.forecolor = Vbwhite

Note that the method mentioned above applies only when you need to manipulate the child objects of an object, and the following code is incorrect:

With Text1
. Text = "Learn VB"
. Alignment = 0
. Tag = "Its I Life"
. BackColor = Vbblack
. ForeColor = Vbwhite
End With

Unfortunately, we can often find code similar to the above in the actual code. Doing so will only make the code more slow to execute. The reason is that the With block is compiled to form a branch, which adds additional processing work.

8. Check whether the string is empty

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

If Text1.Text = "" Then
' Perform action
End If

Unfortunately, the amount of processing required to do string comparisons is even larger than the read attribute. So I suggest you use the following method:

If Len (Text1.Text) = 0 Then
' Perform action
End If

9. Note the variable name after the next keyword

Adding a variable name after the next keyword causes the code to become less efficient. I don't know why, it's just an experience. However, I think very few programmers will be so superfluous, after all, most programmers are cherish words like gold.

' Wrong code
For icount = 1 to 10
' Perform action
Next
' The right Code
For icount = 1 to 10
' Perform action
Next icount

10. Using arrays instead of multiple variables

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

11. Use a dynamic array instead of a static array

Using a dynamic array does not have much impact on the speed of code execution, but in some cases it can save a lot of resources.

12. Destruction of objects

Regardless of what software is written, programmers need to consider releasing the memory space that the software occupies after the user decides to terminate the software's operation. Unfortunately, many programmers don't seem to care much about this. The right thing to do is to destroy the object used in the program before exiting the program. For example:

Dim FSO as New FileSystemObject
' Perform action
' Destroy objects
Set FSO = Nothing
For forms, you can uninstall:
Unload Frmmain

Or

Set frmmain = Nothing

13. Variable length and fixed-length strings

Technically, fixed-length strings require less processing time and space than variable-length strings. But 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 in turn reduces the efficiency of the Code. So unless the length of the string doesn't change, the variable-length string is used.

14. Use class modules instead of ActiveX controls

Unless the ActiveX control involves the user interface, use lightweight objects, such as classes, as much as possible. There is a big difference in the efficiency between the two.

15. Using Internal objects

When it comes to using ActiveX controls and DLLs, many programmers like to compile them and then join the project. I recommend that you do not do this, because the connection from VB to an external object requires a lot of CPU processing power. Every time you invoke a method or access a property, a lot of system resources are wasted. If you have the source code for ActiveX controls or DLLs, use them as private objects for the project.

16. Reduce the number of modules

I agree with the fact that some people like to keep common functions in modules. But it's funny to write only twenty or thirty lines of code in a module. If you're not very much in need of a module, try not to use it. The reason for this is that VB loads modules into memory only when functions or variables in the module are invoked, and when the VB application exits, the modules are unloaded from memory. If there is only one module in the code, VB will only carry out a load operation, so that the efficiency of the code has been improved; Conversely, if there are multiple modules in the code, VB will carry out multiple loading operations, the efficiency of the code will be reduced.

17. Using an array of objects

When designing the user interface, for the same type of control, programmers should use an array of objects as much as possible. You can do an experiment: add 100 PictureBox to the window, each PictureBox has a different name, run the program. Then create a new project, also add 100 PictureBox to the window, but this time using an array of objects, run the program, you can notice the difference in the loading time of two programs.

18. Using the Move method

Some programmers prefer to use the width,height,top and left properties when changing the position of an object. For example:

Image1.width = 100
Image1.height = 100
Image1.top = 0
Image1.left = 0

This is actually inefficient because the program modifies four properties and the window is redrawn after each modification. The correct approach is to use the Move method:

Image1.move 0,0,100,100

19. Reduce the use of pictures

Pictures will take up a lot of memory, and processing pictures also requires a lot of CPU resources. In software, if possible, consider using a background color instead of a picture--which, of course, is only viewed from a technical point of view.

20. Use an ActiveX DLL instead of an ActiveX control

If you design an ActiveX object that does not involve the user interface, use an ActiveX DLL.



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.