Mar 3rd, 2008, 05:04 PM
Classic VB - Why shouldn't I use "Dim .. As New .."?
While using "Dim .. as New .." saves you 1 line of code, it adds problems that are best avoided.
First of all it makes your code slower, as the variable is not created immediately - instead every time you use that variable VB checks if it has been Set yet, and if not it gets Set.
The speed issue is not often a major problem, but the other issues are. As the variable will get Set any time it is used, you can easily (accidentally) Set the object again after you have unloaded it, so it remains in memory. Not only is the memory wasted, but the chances are that your code isn't doing what you intended it to do - but you wont be told why, as there will be no error to say the object isn't Set (and will probably only notice if it does something that is blatantly wrong, which isn't always the case).
Instead of using a single line "Dim variable as New DataType", you should use a separate Dim and Set lines like this:
When you have finished with it, unload it (and release the memory that was used) by setting it to Nothing:
'no "New"! this specifies the data type of the variable, and reserves the memory for it
Dim variable as DataType
'this creates a new instance of the object, and places it into the variable
Set variable = New DataType
Set variable = Nothing
Last edited by si_the_geek; Mar 4th, 2008 at 12:12 PM.
Click Here to Expand Forum to Full Width
Survey posted by VBForums.