When you declare a variable Dim X As New ..., Visual Basic doesn't actually initialize the variable until it uses it. Every time you refer to the variable Visual Basic needs to see if the variable has been initialized and initialize it if it hasn't. It essentially does something like this:
If X Is Nothing Then allocate X
Now do what the program says
The idea is Visual Basic cannot really know apriori whether the variable has been allocated yet.
If you declare the variable and initilize it separately, Visual Basic assumes you know what you're doing and that you will allocate the variable before you use it. If you don't, it raises an error.
This code creates two object variables. The variable emp1 is declared As New while variable emp2 is declared and initialized in separate statements. The program then references the objects' properties many times in loops. In my tests, Dim As New took about 20 percent longer than separate declaration and assignment statements.
Either way is still very fast, however, so for most programs it's not worth worrying about. On my computer, I had to repeat the loops 10 million times to get a consistent meaningful result. The difference is roughly 0.00000004 seconds per object reference. It's just not that much time.
|