Aivosto's Visual Basic tips
This article teaches you a few easy ways to write better VB code.
In this article:
Optimize for memory
Get rid of dead codeDead code means unnecessary, inoperative code that can be removed.
Dead code includes functions and sub-programs that are never called, properties that are never read or written, constants and enums that are never referenced. Dead variables are ones that are never read - even if they've been given a value. User-defined types can also be dead, and there may be a lot of extra API declarations. Even whole files can sometimes be completely unnecessary.
Dead code leads to excessive memory use, slower execucation, larger .exe files, higher maintenance effort and errors. That's why it's important to clean your projects by removal of dead code. Read more about dead code removal
Avoid fixed-length StringsFixed-length strings generally 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.
If you're planning to migrate to VB.NET, then you have one more reason why not to use fixed-length strings. VB.NET doesn't support them natively. You get better performance with variable-length strings. Read more about migrating to VB.NET
Avoid static variablesStatic 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.
Local are those variables and arrays that are declared inside a procedure.
So why should you avoid static local variables? Static variables are slower and consume memory. It is better to use normal, dynamic local variables.
If you really need a static local variable, use a private module-level variable instead. There is a drawback with this, though. You should keep other procedures from using the same variable to avoid unwanted side-effects.
Reclaim memory after useIf 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.
Reclaim memory from arraysArrays 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
Type your variablesVB's default data type is Variant. All variables that don't have any other type are implicit Variants.
Avoid variants when possible. They are slow, and they consume memory. If you use variant instead of, say, integer you waste 14 bytes of memory. This can be significant in a large project. Integers are much faster than variants. This is true particularly in For..Next loops.
Use Option Explicit to force declaration of your variables. This helps you to get rid of unnecessary variants.
Aivosto Project Analyzer can help you to ensure properly typed variables. It can list the implicit Variants and missing Option Explicit statements for you. Typing your variables is a very good habit and a sign of professional development.
Memory optimizations with graphicsGraphics may use a lot of memory and also slow your program down. Here are some easy tips to avoid that.
Optimize for speedUsers are often complaining about slow programs. They may have slightly old computers, but usually it is the developer to blame. How to make apps faster?
Some memory optimizations described in the previous chapter contribute to speed optimization too. These are getting rid of dead code and using appropriate variable types instead of Variants. On many occasions, when you minimize memory usage you will also minimize execution time. In some cases, however, the two goals may be contradictory.
Aivosto VB Watch Profiler is a performance measurement tool that can help you squeeze the most out of your code. It measures the time your code takes to execute - line by line, procedure by procedure. You can make before-after comparisons and check which algorithm is the best one to use. You can also find the bottleneck areas in your project - the areas where you can achieve maximal performance boost with minimal effort.
Now let's see some ways to make faster code.
Optimize string handling
String processing often takes more time than necessary due to unoptimal use of VB functions. Read more about optimized string programming
Cache properties in variablesIf you are going to need the value of a property more than once, assign it to a variable. Variables are generally 10 to 20 times faster than properties of the same type.
Use For Each..NextCollections allow you to iterate through them using an index variable style
Check for loopsNormally, loops are those parts of a program that take the most time to execute. The worst thing is several loops nested.
You can use Aivosto Project Analyzer to find out where the deepest loops are in your code.
You may have heard of mathematical complexity measures like O(n) and O(n2). O(n) means that the execution time of a procedure is proportional to the input size n. O(n2) means it's proportional to the square of the input size. In other words, O(n) is much faster than O(n2), if n is large.
What is n, the input size? It can be anything, including the number of lines in a text file, the dimensions of an array, or the size of binary data. It all depends on what you're programming.
The worst case is denoted by O(2n). This means that execution time rises exponentially when n increases. On the other hand, if execution time rises only logarithmically, like O(log n), you have a fast procedure even for large sets of data.
Very briefly, you calculate mathematical complexity like this:
Mathematical complexity (and the time to execute) is mostly due to the number of nested loops. With a recursive procedure (procedure that calls itself), the problem isn't that simple, but most of VB procedures are not recursive.
Working with objectsMinimize 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:
Now you can refer to
You can use
Early and late bindingIf you know what type an object will be, use that type! Avoid variables declared As Object or As Variant.
This is called early binding - VB knows what type to expect at compile time. The opposite is late binding - the type is known only at run-time. Late binding is much slower. Remember to declare your objects properly!
Optimize display speedOften 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:
How to write understandable codeDo you like spaghetti? No matter if you do or not, you probably don't like spaghetti code.
It is very common to find poorly designed code that is difficult to understand. But that would also be easy to avoid. After all, it is so easy to make understandable code. It doesn't really take a lot of time - but it will save a lot in the future.
Start writing decent code now!Making non-spaghetti code is not about writing a few docs after the program is ready. It is a continuous process that starts at the same time you write the first line of code. Think about the reader that will read the code next year. Will he or she understand the code that has no indentation, meaningless variable names, jumps from place to place, and no comments? Besides, that person might be you!
Aivosto VB Friend is a tool that beautifies your code while you write it. It adds proper indentation and whitespace, and splits complex structures to multiple lines. You can customize it to fits your own personal coding style.
Naming conventionsUse descriptive module, procedure, variable, constant and control names. Longer names tend to be more descriptive.
Use constants instead of numeric values and string literals. Like this:
Global Const APPNAME = "My Fancy Program v1.0" Global Const MAX_SIZE = 32767
Use prefixes for standard naming. There are numerous naming conventions
to choose from. They usually use things like "g" for Global, "i" for
Integer, so giAge would be a global integer for storing someone's age.
Search the web for naming standards and pick your favorite one! Below are a few good starting points.
Aivosto Project Analyzer, especially its Project NameCheck add-in, will be useful with tasks related to ensuring good naming conventions. It alarms if it finds a non-standard name, like a one-letter variable, textbox named Text1, and a global variable missing "g". It even measures how long and descriptive names you use. You can completely customize for your own coding style.
DocumentationComment every procedure, module and the interface to them. A good practice is to put a few comments just after the procedure name, like this:
Document the structure of your project - which module does what, and which modules call which one.
Aivosto Project Analyzer will help you a lot in your documentation tasks. Besides warning about uncommented code, it also generates various kinds of documentation - automatically, straight from your code!
Things to avoidThe usual advice: Don't use GoTo! There is nothing you can't do with If and Do..Loop. The only exception is On Error GoTo. The same advice goes for GoSub too, except that you won't need GoSub at all.
Split complex proceduresOverly 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 (
You probably already guessed that Aivosto Project Analyzer can help you with both finding procedures to split, and also the dreaded GoTo's and GoSub's. It might not come as a surprise that the utility also helps with the next tip, avoiding unintended passing of parameters by reference.
Use ByVal (or ByRef) parametersBy default, all parameters to a VB procedure are passed by reference. Unfortunately, this is not the preferred way in most cases. When you pass by value, you'll get saved from subtle bugs.
When a ByRef parameter is used, the value of the passed argument can be permanently changed by the procedure. Although sometimes you want to use this effect, most of the time it is not what you want.
Consider, for example, the following piece of code:
How much is MyNumber after a call to MultiplyByTwo? It's 14, although one would easily think it's still 7! This happens 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 is easy. Pass the parameter by value using
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:
Now, why would you want to pass by reference? Sometimes you get better performance that way. That's because the contents of the variable are not copied to the sub-procedure. The extra performance comes with a cost though, so use this optimization with care.
Use PrivateWhenever possible, use the keyword
Knowing which thing should be Private and which one Public is difficult, especially if that wasn't taken care of when the original code was written. If a thing is Public when it shouldn't, it's called the excess scope problem. Fortunately, this problem is easy for an automated code analysis to solve. Aivosto Project Analyzer reports excess scope and suggests making things Private whenever possible. Of course, it's up to you to decide if that's really what you want to do.
How to write robust code
Use proper error handlingVB apps crash easily, with messages like "Invalid function call" and "Overflow".
A quick and dirty way to prevent crashes is to use
A more sophisticated solution is to build real error handlers. If an error occurs, display a meaningful error message and give the user the ability to ignore the error, retry, or abort the program. For your own purposes, build and show enough information so that the user may report any bugs to you to fix. Put this in every procedure, and you have a robust program.
Add error handling easilyWork, work, and work! That's what proper error handling requires - unless you have Aivosto VB Watch Protector. VB Watch protects your programs from run-time errors. If one happens, it displays a meaningful error message and gives the user the ability to choose what to do next.
How many times did you hear this: "It just crashed. I don't remember what I was doing. I lost all my data." VB Watch Protector solves this problem. If you want, the users can easily report the bugs together with program status such as procedure name, call stack, code line and variable contents. Imagine fixing the bugs in minutes, not weeks!
How to develop more efficiently
Reuse, reuse, reuse!Reusability is the magic word of programming today. In VB, you can reuse procedures, code modules, or class modules. Reuse greatly reduces the time to develop a program.
You can achieve reusability if you program in an object oriented language creating reusable classes. Although VB isn't a strictly object oriented language, it has a class mechanism called class modules (.cls). VB can also create ActiveX controls - quite a powerful mechanism for reuse.
How do you know if some code is reusable or not? You can use Aivosto Project Analyzer to measure it. Project Analyzer measures the number of incoming calls to a procedure. The larger the number, the more reusable it probably is. Project Analyzer's Super Project Analyzer add-in measures cross-project reuse ratios.
Debugging executablesIt is usually not enough that an application runs on your own computer, or your colleague's one. It must run on the customers' computers too.
Debugging is tough when you have to debug executable files - and that's the way to do it if you have to debug on someone else's computer. That may also be the case when you use ocx or dll files.
VB doesn't have anything to help with this. Fortunately, Aivosto VB Watch Debugger has. It gives you the ability to see inside compiled VB programs, libraries and modules. You can see call stacks, procedure parameters, initialized objects, and call trace - even line-by-line if required.
©Aivosto Oy -