Re: Lots of static variables

Tech-Archive recommends: Speed Up your PC by fixing your registry

From: Rick Rothstein (rickNOSPAMnews_at_NOSPAMcomcast.net)
Date: 02/26/04


Date: Thu, 26 Feb 2004 08:47:31 -0500


> I've recently started maintaining some VB code, and the thing that most
> suprises me is how virtually all variables are declared static. Variables
> with a clearly local meaning in a Sub or Function are declared Static,
> sometimes even including the 'i' in a loop.
>
> I understand the next time I call the procedure the value of static
> variables will be preserved, but most of these variables are explicitly
> initialized every time the function executes anyway. The cases where I've
> found the variable to be semantically static (there is some reason to
> preserve its value) are very rare.
>
> Is there some reason for this? Efficiency? Or is it just plain wrong?

It would be plain wrong... Static variables are somewhat slow as I recall,
so I would change the Static to Dim for the cases you described. However, be
careful regarding those that look initialized. If you have something like
this

     If YourStaticVariable = 0 Then
       YourStaticVariable = <some value other than zero>
     End If

That is a legitimate way of giving a Static variable its "first" value
(assuming it is never supposed to be zero) and will only be executed the
first time the Sub or Function is called. Same with a String variable and
the Empty String ("").

Rick - MVP


Quantcast