Results 1 to 23 of 23

Thread: [RESOLVED] Performance of statuic vs dim variable declaration

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2019
    Posts
    438

    Resolved [RESOLVED] Performance of statuic vs dim variable declaration

    I was wondering if in a very high use function that is properly written if declaring variables as static vs using dim would save any memory allocations and thus perform better.

    any ideas before I launch into benchmarking?

    cheers

  2. #2
    Frenzied Member
    Join Date
    Jun 2015
    Posts
    1,086

    Re: Performance of statuic vs dim variable declaration

    If it was a large array maybe, you would have to still zero it out before use or be careful filling it full though as old values would persist.

    Strings will keep being reallocated as you do stuff. Numerics are just stack allocation so no bonus there really.

    Static vars will have an extra layer or two to look up their location may be on every use never looked closely they could even be slower.

    Private Module level vars might be fastest

  3. #3
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    10,205

    Re: Performance of statuic vs dim variable declaration

    Quote Originally Posted by vbwins View Post
    I was wondering if in a very high use function that is properly written if declaring variables as static vs using dim would save any memory allocations and thus perform better.

    any ideas before I launch into benchmarking?
    You'll definitely get better performance from Static as opposed to Dim, if we're strictly talking about variables local to a specific procedure. Module and global variables (even if declared with Dim or Private or Public or Global) are already Static.



    But, for local procedure numeric variables, the performance increase will be extremely negligible. A "Dim" variable is going to be created on the stack, whereas a "Static" variable's space is created at compile-time. That's basically the whole speed & memory issue. With a local Static, you gain the time needed to create the variable. And also, for any recursive procedure, only one variable gets created as opposed to a new variable for each entry into the procedure.

    If we're talking about local procedure string variables, the gains will be more noticeable.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  4. #4
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    10,205

    Re: Performance of statuic [sic] vs dim variable declaration

    Code:
    
    Option Explicit
    
    Private Sub Form_Load()
    
        Dim n As Long
        Const CNT As Long = &H1FFFFFF
        Dim fStart As Single
        Dim fStop As Single
    
        fStart = Timer
        For n = 1& To CNT
            TestDim
        Next
        fStop = Timer
        Debug.Print "   Dim Seconds: "; fStop - fStart
    
        fStart = Timer
        For n = 1& To CNT
            TestStatic
        Next
        fStop = Timer
        Debug.Print "Static Seconds: "; fStop - fStart
    
    
    
    End Sub
    
    Private Sub TestDim()
        Dim i As Long
        i = 5&
    End Sub
    
    Private Sub TestStatic()
        Static i As Long
        i = 5&
    End Sub
    
    
    My output:

    Code:
       Dim Seconds:  1.164063 
    Static Seconds:  1.417969
    So interestingly, I had it backwards. Static is a bit slower, about 18% slower. It seems that Wqweto and The Trick looked into the reasons for this recently.

    Now, for a recursive procedure that we recurse deep into, the stack demands may be worth considering.
    Last edited by Elroy; May 14th, 2024 at 02:20 PM.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  5. #5
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    10,205

    Re: Performance of statuic [sic] vs dim variable declaration

    Crap, I forgot to change the second call to TestStatic. I'm fixing it now. FIXED!
    Last edited by Elroy; May 14th, 2024 at 02:20 PM.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  6. #6
    PowerPoster
    Join Date
    Feb 2015
    Posts
    2,734

    Re: Performance of statuic [sic] vs dim variable declaration

    Quote Originally Posted by Elroy View Post
    So interestingly, I had it backwards. Static is a bit slower, about 18% slower. It seems that Wqweto and The Trick looked into the reasons for this recently..
    Put your functions to a standard module and compile with all the optimizations. Static variables of an object module are actually module level variables. Another thing is the static and public variables in the public project types (AxDll/AxExe/etc.) with all the threading models except single threading are quite slower.

  7. #7

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2019
    Posts
    438

    Re: Performance of statuic vs dim variable declaration

    I compiled with a listing to look at the asm. This a fragment from the listing. Seems the static involves an extra instruction?

    Code:
    2504 :           Static s1_static As Long
    ; 2505 :           
    ; 2506 : 40        s1_static = 1
    
    	mov	eax, DWORD PTR _mTraceFileActivity+384
    	mov	DWORD PTR [eax+328], 1
    
    ; 2521 : 
    ; 2522 :           Dim s1_dim As Long
    ; 2523 :           
    ; 2524 : 80        s1_dim = 1
    
    	mov	DWORD PTR _s1_dim$[ebp], 1

  8. #8

  9. #9
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,233

    Re: Performance of statuic vs dim variable declaration

    Quote Originally Posted by Elroy View Post
    If we're talking about local procedure string variables, the gains will be more noticeable.
    Btw, most significant gains are actually with arrays. Having a Dim MyBuffer(0 to 1000) As Long in a procedure generates initialization code i.e. allocating *and* setting each element to initial value while Static MyBuffer(0 to 1000) As Long has it done one time before hitting the routine i.e. at module/object (routine in a class) or binary/process (routine in a std module) initialization.

    cheers,
    </wqw>

  10. #10
    PowerPoster
    Join Date
    Feb 2017
    Posts
    5,123

    Re: Performance of statuic vs dim variable declaration

    Quote Originally Posted by dz32 View Post
    Private Module level vars might be fastest
    Yes, I guess that (in a bas module).

  11. #11
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    10,205

    Re: Performance of statuic vs dim variable declaration

    With the TestDim and TestStatic being in a BAS module:

    In IDE:
    Code:
       Dim Seconds:  0.8984375 
    Static Seconds:  1.152344
    Compiled:
    Name:  DimVStatic.png
Views: 95
Size:  3.5 KB

    It seems that a Dim out-performs a Static in pretty much all cases. That truly surprises me.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  12. #12

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2019
    Posts
    438

    Re: Performance of statuic [sic] vs dim variable declaration

    Quote Originally Posted by The trick View Post
    Put to a standard module and it won't generate additional instruction.
    It's in a standard module but local to a function. Do you mean declare at module level?

  13. #13
    The Idiot
    Join Date
    Dec 2014
    Posts
    2,747

    Re: Performance of statuic vs dim variable declaration

    Elroy, did u also check adding a Dim in the module (its like static but for the entire module) or just public/private dim
    and see the difference in speed

    the only thing I can think of "why" static is slower is that everytime u enter the function it need to assign the value to the variable.

  14. #14
    PowerPoster
    Join Date
    Feb 2017
    Posts
    5,123

    Re: Performance of statuic vs dim variable declaration

    Surprisingly, module level variables are slower.

    Name:  InIDE.png
Views: 77
Size:  7.3 KB

    Name:  Compiled.png
Views: 79
Size:  6.4 KB
    Attached Files Attached Files

  15. #15
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    10,205

    Re: Performance of statuic vs dim variable declaration

    So, the take-home is, forget Static unless we've got some procedure level value we'd like to hang onto between calls, or, if it's a recursive procedure and we're worried about piling variables up in the stack.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  16. #16
    PowerPoster
    Join Date
    Feb 2015
    Posts
    2,734

    Re: Performance of statuic vs dim variable declaration

    Guys, you don't consider VB6 optimizations.
    Such code:

    Code:
    Public Sub TestDimBas()
        Dim i As Long
        
        If i = 1 Then
            i = 5&
        Else
            i = 1&
        End If
    End Sub
    is optimized by compiler and unused local variable is discarded. So it becomes just:

    Code:
    Public Sub TestDimBas()
    End Sub
    Object methods always slower than native functions. VB6 compiler quite smart and can do some precalculations for local variables whereas it couldn't do it for static and module level variables are accessed by many procedures.

    The more correct test:

    Code:
    Option Explicit
    
    Private im As Long
    Public Sub TestDimBas()
        Dim i As Long
    
        foo i
        
    End Sub
    
    Public Sub TestStaticBas()
        Static i As Long
    
        foo i
     
    End Sub
    
    Public Sub TestModuleLevelBas()
    
        foo im
     
    End Sub
    
    Public Sub foo(ByRef i As Long)
    
    End Sub
    We pass the reference to variable to an external function which removes most of optimizations.


  17. #17
    PowerPoster
    Join Date
    Feb 2017
    Posts
    5,123

    Re: Performance of statuic vs dim variable declaration

    Hello, Trick, I've made changes to use the variables but not as per your example (just to make the changes quicker).
    Please tell me if that could be enough to do it right.

    Name:  InIDE2.png
Views: 64
Size:  6.4 KB

    Name:  Compiled2.png
Views: 62
Size:  6.2 KB
    Attached Files Attached Files

  18. #18

  19. #19
    PowerPoster
    Join Date
    Feb 2017
    Posts
    5,123

    Re: Performance of statuic vs dim variable declaration

    Quote Originally Posted by The trick View Post
    Code:
    Public Function TestDimBas() As Long
        Dim i As Long
        
        If i = 1 Then
            i = 5&
        Else
            i = 1&
        End If
        TestDimBas = i
    End Function
    This value is precalculated at compile time. There is NO local variable at all in the compiled exe.
    Yes, I see that I used the logic intended for static variables to Dimmed ones....

  20. #20

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2019
    Posts
    438

    Re: Performance of statuic vs dim variable declaration

    Thanks gang. Super interesting discussion. I have changed my statics to dim in my time critical project. Does this all come down to dim being allocated on the stack and static being in the heap?

    I am going to try with arrays later today to see what the performance is of dim vs static

  21. #21

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2019
    Posts
    438

    Re: Performance of statuic vs dim variable declaration

    With the code below static is much faster than dim for arrays unless I messed up something. 3.38 vs 70.8 when compiled with all options on.


    Code:
    Option Explicit
    Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As Currency) As Long
    
    Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As Currency) As Long
    Private Sub Form_Load()
        Const lCount As Long = 1000000
        
        Dim r As Long
        
        Dim i As Long
        
        Dim startTime As Currency
        
        Dim endTime As Currency
        
        QueryPerformanceCounter startTime
        
        For i = 0 To lCount
        
            r = staticArray
            
        Next i
        
        QueryPerformanceCounter endTime
        
        Form1.List1.AddItem "Static " & endTime - startTime
        
        QueryPerformanceCounter startTime
        
        For i = 0 To lCount
        
            r = dimArray
            
        Next i
        
        QueryPerformanceCounter endTime
        
        Form1.List1.AddItem "Dim " & endTime - startTime
    
    End Sub
    Private Function staticArray() As Long
        Const upper As Long = 4
        
        Static myLong(upper) As Long
        
        Dim i As Long
        
        For i = 0 To upper
        
            myLong(0) = i
            
            myLong(1) = i
            
            myLong(2) = i
            
            myLong(3) = i
            
            myLong(4) = i
            
       Next i
       
       staticArray = myLong(0) + myLong(1) + myLong(2) + myLong(3) + myLong(4)
       
    End Function
    
    Private Function dimArray() As Long
        Const upper As Long = 4
        
        Dim myLong(upper) As Long
        
        Dim i As Long
        
        For i = 0 To upper
        
            myLong(0) = i
            
            myLong(1) = i
            
            myLong(2) = i
            
            myLong(3) = i
            
            myLong(4) = i
            
       Next i
       
       dimArray = myLong(0) + myLong(1) + myLong(2) + myLong(3) + myLong(4)
       
    End Function

  22. #22
    Frenzied Member VanGoghGaming's Avatar
    Join Date
    Jan 2020
    Location
    Eve Online - Mining, Missions & Market Trading!
    Posts
    1,543

    Lightbulb Re: Performance of statuic vs dim variable declaration

    That's because the array is zeroed out every time for the non-static version.

  23. #23
    PowerPoster
    Join Date
    Feb 2015
    Posts
    2,734

    Re: Performance of statuic vs dim variable declaration

    Quote Originally Posted by vbwins View Post
    Does this all come down to dim being allocated on the stack and static being in the heap?
    There are the different cases. If we don't touch the referenced data placement (which always are in the dynamic memory) the local procedure variables are in the stack (or sometimes in the registers). The public/private variables inside the standard modules (or static ones in the procedures in the standard modules) may lay as in the .data section of an executable as in the dynamic memory too. It depends on the apartment and threading model of the project.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width