Visual Basic tips for optimizing your code |
The tips were collected by Tuomas Salste, a BASIC programmer since 1985, and a Visual Basic programmer since 1993.
Shareware tools for Visual Basic programmers. Tips and user survey results
This page includes some tips on
If you need more tips, check some VB Books!
Project Analyzer helps you to find all dead code.
VB's default data type is Variant. Avoid Variants when possible. They are slow, and they consume memory.
Use Option Explicit to force declaration of your variables. This helps you to get rid of unnecessary Variants.
Project Analyzer helps you to find missing Option Explicits and implicit Variants.
Fixed-length strings occupy more memory than variable-length ones. The problem is worse if you have to reserve lots of space for long strings in your fixed-length String variables.
Static variables are those that reside in the memory for the whole execution time. The opposite of static variables are dynamic variables. Dynamic variables are procedure-level variables that are created when the procedure is entered, and destroyed when the procedure ends.
Use the following table to determine whether your variables and arrays are static or dynamic.
Variables | Arrays | |
---|---|---|
Static |
|
|
Dynamic |
|
|
If you are using static variables, it's important to reclaim the memory they occupied when you don't need the variables any more. With dynamic variables memory isn't so much of a problem, because they are destroyed when the procedure ends.
The below table shows how you can reclaim the memory occupied by different variable types. Arrays are discussed below the table.
Type of variable | Code to reclaim occupied space |
---|---|
Variable-length String | MyString = "" |
Variant | MyVariant = Empty |
Form | Unload MyForm |
Object | Set MyObjectVariable = Nothing |
Arrays are often memory-hungry. This applies especially to static arrays, whose size is fixed for the lifetime of the program. Dynamic arrays are better for memory optimizations, because they can be resized. However, some memory optimization can be applied to both array types.
One way to reclaim space occupied by an array is to clear all
its elements one by one as shown above. Another way is to use Erase
or ReDim
.
Erase
frees the memory used by
dynamic arrays. With static arrays, however, the effect
is somewhat limited. Doing Erase
for a
static array is the same as clearing all its elements
separately. ReDim
can be used only for dynamic
arrays. You can ReDim
a dynamic array to a
smaller size. If you just want to reduce the array and
still preserve some data in it, you can use ReDim
Preserve
, like this: ReDim Preserve
MyArray(SmallerSize)
LoadPicture()
and Cls
.Picture
property to Nothing
(VB 4.0 and later). MyGraph.Picture = OldGraph.Picture
AutoRedraw = False
. If it's True
,
VB will create an AutoRedraw image that consumes memory. Now some ways to make faster code.
For Each..Next
instead of
For(
index
)..Next
Very briefly, you calculate mathematical complexity like this:
Project Analyzer detects nested loops, which is a very rough estimate of mathematical complexity.
Minimize the dots. Each dot consumes some time, and makes the code more difficult to read. You can refer to an object's default property just with the name of the object (without the name of the property!). You can also assign an object to an object variable, like this:
Dim X As SomeObject Set X = SomeContainer.SomeObject(123)
Now you can refer to X
instead of the long
expression SomeContainer.SomeObject(123)
. In VB 4.0
and later you can use With..End With
for the same
effect.
Use early binding. If you know what the type of an object will
be, declare your variables with that type. Avoid variables of the
general type Object
as long as you can. Use the
specific type instead.
Often it's important how fast your application appears to run, even if the the actual speed isn't that high. Some ways to speed up display speed:
DoEvents
.
A good place to put DoEvents
is inside
time-consuming loops. This needs some consideration,
because the user might click some buttons, for example,
and your program must know what the user is allowed to do
when the background process is running. Set flags like
Processing=True and check them in appropriate places. Global Const APPNAME = "My Fancy Program v1.0" Global Const MAX_SIZE = 32767
Function FileAge(ByVal Filename As String) As Long ' Detects how old the file Filename is. ' Returns the age of the file in days, -1 in the case an error occurs. ' Includes error handling.
Goto
! There is nothing you can't do with
If
and Do..Loop
. The only
exception is On Error Goto
. Project Analyzer generates extensive project documentation with your comments included. It also measures the length of names.
Overly long and complex procedures are hard to understand.
They are error-prone. One particular sign of a complex procedure
is the amount of nested conditionals (if, do..loop, select
case
).
Project Analyzer detects complex procedures in a number of ways.
By default, all parameters to a VB procedure are passed by reference. Consider, for example, the following piece of code:
Function MultiplyByTwo(x As Integer) As Integer x = x * 2 MultiplyByTwo = x End Function ... MyNumber = 7 Debug.Print MultiplyByTwo(MyNumber)
How much is MyNumber after a call to MultiplyByTwo? It's 14, although one would easily think it's still 7!
This is because MultiplyByTwo doubles the value of parameter x before returning it back, and the change reflects in MyNumber. In fact, passing parameters by reference means that MyNumber and x are the same variable!
The solution to this is easy. Pass the parameter by value
using ByVal
, like this:
Function MultiplyByTwo(ByVal x As Integer) As Integer
Now, even if MultiplyByTwo changes the value of x, it will never change the value of MyNumber in the calling procedure.
If you really want to use by reference passing, use it explicitly like this:
Function MultiplyByTwo(ByRef x As Integer) As Integer
Whenever possible, use the keyword Private
. This
will make your procedures and variables accessible inside the
module only. The advantage is increased modularity in your code.
Private MyVariable As Integer Private Sub MyProcedure()
Project Analyzer detects variables, constants and procedures that could be declared Private.
To tackle this problem, design error handlers carefully. To test them, you may use DB Lock.
Project Analyzer measures reusability in 2 ways:
Problems experienced by VB users.
Other programming languages used by VB programmers.