|
Quick comparison among UDTs
|
Total Hit (4244) |
When you need to compare two User Defined Type (UDT) variables to check whether they are equal, the only approach that you can follow in plain VB is to compare each individual element of the UDT. For example, say that you have the following Type declaration:
«Code LangId=1»
Private Type MyUDT
....Read More |
Rating
|
|
|
Reduce the number of DoEvents
|
Total Hit (4550) |
Don't fill your code with unnecessary DoEvents statements, especially within time-critical loops. If you can't avoid that, at least you can reduce the overhead by invoking DoEvents only every N iterations of the loop, using a statement like this:
«Code LangId=1»
If (loopNdx Mod 10) = 0 Then DoEv
....Read More |
Rating
|
|
|
REMark out a group of lines
|
Total Hit (4405) |
VB5 and VB6 environments include a pair hidden commands that let you remark and unremark a group of statements. These commands are hidden in the sense that they can be found on the secondary Edit toolbar that isn't displayed by default. To make these commands available, right-click anywhere on the m
....Read More |
Rating
|
|
|
Remove collection items from the beginning
|
Total Hit (3346) |
There are many different ways to delete all the items in a collection, but some of them are much faster than the others. Let's start with a collection that holds 10,000 items:
«Code LangId=1»
Dim col As New Collection, i As Long
For i = 1 To 10000
col.Add i, CStr(i)
Next
«/Code»
You can d
....Read More |
Rating
|
|
|
Short-circuit evaluation with Select Case
|
Total Hit (3941) |
Short-circuit evaluation is an optimization technique automatically adopted by most modern compilers, including all flavors of C++, Borland Delphi and many others. Unfortunately, the Visual Basic compiler is not in this group. This optimization cuts down the time needed to evaluate a boolean express
....Read More |
Rating
|
|
|
Simplify and optimize expressions with And, Or and Xor operators
|
Total Hit (3295) |
Let's assume you must test whether the most significan bit of an integer value is set or not. This is the code that you usually write:
' two cases, depending on whether the value is Integer or Long
If intValue And &H8000 Then
' most significant bit is set
End If
If lngValue And &H8000000
....Read More |
Rating
|
|
|
Simplify your code with Inc and Dec functions
|
Total Hit (3500) |
Unlike other languages - such as C and Delphi - VB lacks of the capability to increment and decrement a variable. Adding this feature, in the form of reusable Function routines, is simple:
«Code LangId=1»
Function Inc(Value As Variant, Optional Increment As Variant = 1) As Variant
Value = V
....Read More |
Rating
|
|
|
Static Variables are slower than Dynamic ones
|
Total Hit (3970) |
Referencing a static local variable in a procedure is 2-3 times slower than a regular local, dynamic variable; if you want to really speed up your procedures, convert all static variables into module-level variables.
The only drawback to this approach is that the procedure become less self-conta
....Read More |
Rating
|
|
|
Terminate the process with an ErrorLevel code
|
Total Hit (3673) |
If your VB application is meant to be called from within a Ms-Dos batch file, you must be able to return Dos an error code. This can be accomplished using the ExitProcess API function:
«Code LangId=1»
Private Declare Sub ExitProcess Lib "kernel32" (ByVal uExitCode As Long)
' terminate the pro
....Read More |
Rating
|
|
|
Testing a key in a PropertyBag without raising an error
|
Total Hit (3114) |
When you pass a non-existing key to the WriteProperty method of the PropertyBag object you get an error 327 "Data value named 'namekey' not found". This is more or less the same error - albeit with a different error code - that you receive when you pass an non-existing key to the Item method of a Co
....Read More |
Rating
|
|
|
The "Assume No Aliasing" compiler option
|
Total Hit (2994) |
A procedure is said to contain aliased values if it can refer to the same memory addresses in two or more distinct ways. A typical example is the following procedure:
«Code LangId=1»
Dim g_GlobalVariable As Long
...
Sub ProcWithAliases(x As Long)
x = x + 1
g_GlobalVariable = g_GlobalV
....Read More |
Rating
|
|
|
Use ActiveControl to stop a loop
|
Total Hit (3101) |
Often your user interface includes fields whose contents mutually depends on other fields. A typical example is when you deal with conversions from one measurement unit to another. Let's say that you want to let your users enter a temperature either in Celsius or Fahrenheit degrees, so you provide t
....Read More |
Rating
|
|
|
Use function name as a local variable
|
Total Hit (3350) |
Many programmers don't realize that it is perfectly legal to use the name of a function inside the Function itself, as if it were a local variable. This trick often lets you avoid the declaration of a temporary variable, and sometimes can speed up the code. Take for example the following code:
«
....Read More |
Rating
|
|
|
Use the right type for constants
|
Total Hit (3115) |
VB stores symbolic and literal constants internally using the simplest data type possible; this means that most common numeric constants-such as zero or one-are stored as Integers. If you use these constants in floating point expressions you can speed up your code using a constant of appropriate typ
....Read More |
Rating
|
|
|
Write concise code with Boolean expressions
|
Total Hit (3101) |
When setting a Boolean value based upon the result of an expression, avoid using an unnecessary If/Then/Else structure.
«Code LangId=1»
'Instead of using this lengthy syntax . . .
If SomeVar > SomeOtherVar Then
BoolVal = True
Else
BoolVal = False
End If
'Use this one, which is easi
....Read More |
Rating
|
|
|
Write concise code with the Choose function
|
Total Hit (2935) |
The Choose function lets you often make more concise, albeit not faster, code, because it lets you replace a lengthy Select Case block. For example, the following code:
«Code LangId=1»
Select Case index
Case 1
result = 100
Case 2
result = 250
Case 3
resu
....Read More |
Rating
|
|
|
Evaluate an expression at runtime
|
Total Hit (3618) |
The .NET framework doesn't offer any direct way to evaluate an expression that has been entered by the end user when the application is running. However, it is quite simple to create a simple expression evaluator based on calculated columns in DataTable. The following routine does the trick:
«Cod
....Read More |
Rating
|
|
|
Event logging doesn't work in interpreted applications
|
Total Hit (3495) |
The StartLogging and LogEvent methods of the App object only work in compiled applications. This behavior is by design and shouldn't be considered a bug, even though it isn't documented in the language manuals.
To work around this problem, just create an ActiveX DLL component that exposes the St
....Read More |
Rating
|
|
|
GoSub are slower in compiled programs
|
Total Hit (3428) |
In VB applications compiled as native code, GoSubs are 5-6 times slower than calls to regular Subs or Functions; conversely, in p-code they are considerably faster. This is one of the few examples of an optimization rule that is different in p-code from compiled applications.
....Read More |
Rating
|
|
|
Hidden Variant variables
|
Total Hit (3520) |
Variants are the default type of variables that are declared without an As clause, as in:
«Code LangId=1»
Dim name ' this is a variant
«/Code»
or are not declared at all (which is only possible if the current module does not include any Option Explicit statement). If you are recycling progra
....Read More |
Rating
|
|
|
Implement the CallByName function using the TLI library
|
Total Hit (5494) |
Thanks to the undocumented TlbInf32 library you can emulate the VB6 CallByName() function in VB5 too. First, add a reference to the "TypeLib Information" type library in your project. This library contains the InvokeHook function, which is very similar to CallByName.
Let's suppose you have an Act
....Read More |
Rating
|
|
|
Interpreted or Compiled?
|
Total Hit (4098) |
It is highly unfortunate that Visual Basic doesn't offer a way to execute a group of statements only when the program is interpreted in the environment or only when it has been compiled (indifferently as native code or p-code) to an EXE file. What we badly need is a conditional compilation constant
....Read More |
Rating
|
|
|
IsMissing returns False with non-Variant arguments
|
Total Hit (3638) |
Every now and then I forget that the IsMissing function always returns False when the argument is not a Variant value. This happens because IsMissing does nothing more than converting its argument to Variant and testing for a special VarType value. For this reason, the following code is a symptom of
....Read More |
Rating
|
|
|
Items of ParamArray can be Missing
|
Total Hit (3437) |
When using the ParamArray keyword within a procedure, always remember that when the procedure is invoked from elsewhere in the program one of the argument might be omitted, and you should keep this into account. Here is an example of a routine that uses ParamArray:
«Code LangId=1»
Function Max(
....Read More |
Rating
|
|
|
LenB has changed from VB5 to VB6
|
Total Hit (4361) |
Visual Basic stores UDTs in unpacked format, that is it alignes all UDT elements to the double word (except that Integers and Boolean are aligned to the word, and byte elements aren't aligned at all). To keep the elements aligned VB adds padding bytes where necessary. For instance the structure:
«
....Read More |
Rating
|
|
|
Manufacture a Missing value
|
Total Hit (3938) |
Visual Basic doesn't provide you with a means for creating a Missing value, a feature that in some cases would prove useful in order to simplify the syntax of calls to procedures that expects a variable number of arguments. It isn't difficult, however, to create such a value programmatically, as fol
....Read More |
Rating
|
|
|
Missing Option Explicit directives
|
Total Hit (3347) |
The single statement that is most useful to avoid bugs is Option Explicit. Always use it in every module of your applications. Even better, let the Visual Basic IDE automatically add one whenever you create a new module to your project. You can do it by selecting the "Require Variable Declarations"
....Read More |
Rating
|
|
|
Never use the End statement
|
Total Hit (3658) |
There are a lot of risks involved in using End in VB programs: your databases might not be correctly closed, your objects are not correctly terminated, etc. You should always terminate a program by unloading all the forms. You can do this using the following routine:
«Code LangId=1»
For index = F
....Read More |
Rating
|
|
|
Persistent breakpoints
|
Total Hit (3361) |
When you close a VB IDE session, VB saves the code but doesn't save the current set of breakpoints. If you need (non-conditional) breakpoints to persist among sessions, don't use the F9 key. Instead, use the following statement
«Code LangId=1»
Debug.Assert False
«/Code»
The above code will alwa
....Read More |
Rating
|
|
|
Property Procedures in BAS modules
|
Total Hit (3588) |
Visual Basic supports Property procedures to implement properties in your own CLS and FRM modules. However, it turns out that you can use Property procedures even within BAS code modules.
How can this improve your programming skills? In many a way, as I will demonstrate. Say your program include
....Read More |
Rating
|
|