Results 1 to 40 of 77

Thread: tips for optimizing vb code

Hybrid View

  1. #1

    Thread Starter
    Hyperactive Member Maven's Avatar
    Join Date
    Feb 2003
    Location
    Greeneville, TN
    Posts
    322

    tips for optimizing vb code

    There is only so much you can do with optimizing vb code. The largest reason for this is due to visual basic hiding so much from us and of course the lack of “umph” in the language itself. If you want lighting fast code then you really have no choice but to write a dll file in another language and calling it from visual basic. I'm not going to go down that road in this tutorial but attempt to show you a few methods to help speed up visual basic code. Hopefully this tutorial will help a few of the newer programmers and also teach the old ones a few new tricks =)

    A few Notes:
    It's important to know the compiler options of visual basic. You want to compile to native code and not p-code. P-code stands for pseudo code, which means that your instructions will be translated at runtime and will make your program run a lot slower. You also have more options when you compile to native code. One of the big ones is:
    “Assume No Aliasing (Advanced Optimization)”. If your not passing variables via byref then always check that. Microsoft warns that if you have variables passed byref to functions that it could cause the code to run incorrectly. In a nutshell, no matter what language you use, always read up on the compiler options. You can read more about visual basics compiler options in the msdn library.

    One thing I suggest all programmers do is to learn assembler. If you don't know it, then you should add “Learn Assembler” on you're todo list. Don't go for online tutorials either, you should buy a good book and not put it down till you know how to write ASM. You simply don't know how things work until you know assembler and knowing how things work is a must to writing fast code. Assembler is where you unlock all the secrets that I'm sure you've asked at some point. It's where you learn “Why”.

    Creating fast code does have a few drawbacks. Code that is optimized can be very cryptic** to read. So make sure you always comment optimized code well, or you may find yourself thinking “What was I doing here?”. Another drawback is program size. You may find yourself making program size vs program speed decisions.

    Before you sit down and start optimizing code, you first need to do something. That is, you need to identify the critical parts of your code. In other words, you need to identify the code that NEEDS optimizing. Loops and complex calculation algorithms are the two most important things to look at. Many programmers have completely wasted their time by optimizing things in their application that doesn't mean squat. You also need to know that you cannot optimize code that isn't yours. For example, you cannot optimize code in the windows API or 3rd party controls that your application uses. When you're working with 3rd party stuff, there is very little you can do short of re-writing it.

    Use the GetTickCount API to time your code, though you may have to loop some of it quite a bit to see the effects of it. I may try to write a dll in asm later on that makes use of the rdtsc instruction, that you would be able to call from visual basic and get clock cycles that your code uses. If I manage to get it to work with visual basic it would be better to profile your code with it as you wouldn't need gettickcount or have to loop your code a lot. It's a very exotic feature that would be nice to have in visual basic.

    Enough of the notes, lets start learning code optimization.

    Tip #1 – Move as much code as possible outside of loops.
    Loops are always the most important thing to optimize in your code. Always try to move as much as you can out of a loop. That way code doesn't get repeated and saves you some cpu cycles. A simple example:

    Code:
    for i = 1 to 50
    x = b		' Stays the same with every loop, get it outside of the loop!
    k = j + i
    next i
    Change that to:

    Code:
    x = b	'Moved outside the loop
    
    for i = 1 to 50
    	k = j + 1
    next i
    That may seem like a no-brainier but you would be surprised about how many programmers do that. The simple rule is, if it doesn't change with every loop iteration then move it outside of the loop as it doesn't need to be there. You only want to include code inside a loop that MUST be there. The more instructions you can clear out of a loop the faster we can run it.

    Tip #2 – Loop Unrolling
    Loop unrolling can eliminate some compare and jump instructions. (Compare and jump instructions are used to create loops, you don't see them in visual basic, its behind the scenes stuff that you learn in ASM.) It also takes advantage of the ability of modern cpus that can fetch several instructions at a time. In a nutshell you get a good speed boast by unrolling loops.

    But there is something we need to know about loop unrolling. The largest bottleneck on modern computers is memory. So the designers of CPU's like Intel and AMD addressed this problem by using a cache on their cpus. This is basically a memory location that is accessed much faster by the CPU then standard memory. You want your unrolled loop to fit in that cache, if it doesn't then it could slow down your code. So you may want to experiment with gettickcount when you unroll you're loop.

    Example Loop:
    Code:
    For i = 1 To 100
            b = somefun(b)
    Next i
    unrolled Example:
    Code:
    For i = 1 To 100 step 2
            b = somefun(b)
            b = somefun(b)
    Next i
    You can get up to a 25% gain in speed depending on what you are doing, you just have to experiment with this.

    Tip #3 – Avoid dividing if possible.
    A divide instruction is one of the most if not the most expensive instruction you can perform on a CPU. It is faster to multiply then divide!

    Code:
    B = 40 / 2
    is slower then
    Code:
    b = 40 * 0.5
    You can also develop some interesting algorithms using subtraction to get your result that is much faster then using division. If your using division in a loop, it is a must to change it to speed up your code. (I was going to also recommend trying shifting the bits for division but I forgot some versions of visual basic doesn't include the shift operator).

    Tip #4 – In a nested conditional branch such as select case and nested if statements, put the things that are most likely to be true first in the nest, with the least likely things last.

    Tip #5 – Avoid use of variant variables.
    The variant variable is all nice when you are new to visual basic, but its a habit you need to break. A variant variable is converted into its proper data type at runtime which can be very expensive.

    Tip #6 – Be careful when you declare variables.
    If you don't use as something with every variable you declare, it is a variant! For example:
    Code:
    Dim a, b, c as string.
    A = A variant
    B = A variant
    C = A string
    I've seen some people use the notation:
    Code:
    dim x
    x = blah
    that is a NO NO! It may work yes, but its going to cost you speed.

    Tip #7 – Reduce common expressions.
    Sometimes you have two different variables that use part of the same calculation. Instead of doing the entire calculation for both variables, eliminate the redundant calculation.

    Example:
    Code:
    x = a * b + c
    y = a * b + d
    is slower then
    Code:
    t = a * b
    x = t + c
    y = t + d
    That is especially true if your using a redundant expensive calculation in a loop.

    Tip # 7 – Use long or integer for calculations.
    A long is a 32 bit number and is more natural on 32 bit processors. Avoid other variables such as double, single, etc

    Tip #8 – Use inline functions inside of loops.
    Instead of calling a function, stick the code in the loop. This will make you're program larger if you repeat it in enough loops and should only be done in critical places. The reason is due to the over head of calling a function. Before the program calls a function, it has to push some things onto the stack. At the very least it will push the instruction pointer (IE: Return Address). Memory access is slow so we want to avoid that in critical places.

    Tip #9 Avoid using properties in loops.
    Properties are accessed a lot slower then variables, so use variables instead:

    Code:
    for i = 1 to 50
    text1.text = text1.text + b(i)
    next i
    is slower then
    Code:
    for i = 1 to 50
    strbuffer = strbuffer + b(i)
    next i
    text1.text = strbuffer
    Tip #10 – Load all the data you need from the disk.
    Instead of loading one file at a time, load all of them at once. This will avoid future delay for the user.

    Tip #11 – Make good use of the timer control.
    You can do background processing while waiting on a user. Use this time to prefetch data, calculations that are need, etc.

    Tip #12 – Minimize dot notation in your objects!
    Each dot you use in a object makes visual basic do a call.

    Code:
    Myobject.one.two.three
    is slower then
    Code:
    Myobject.one
    Tip #13 Allocate enough memory at once.
    When you create a dynamic array and you want to add elements that haven't been allocated yet, make sure you allocate enough for all of them instead of doing it one at a time. If you don't know how many you need, times what you have allocated by 2. Allocating memory is a expensive process.

    Tip #14 Avoid built in functions in loops.
    If you have a algorithm that is looped that requires the len of your string. Make sure you cache the size of your string in a buffer and not call the function len() with each iteration of the loop:
    Code:
    for i = 1 to 100
    	sz = len(string)
    	'Do processing
    next i
    instead

    Code:
    sz = len(string)
    for i = 1 to 100
    	'Do Processing with sz
    next i
    Tip #15 Hide the control when your setting its properties.
    Every time you update the properties of your control, you make it repaint. So if your developing something that displays complex graphics, may be a good idea to reduce that from happening so much.
    Last edited by Maven; Dec 9th, 2004 at 12:06 PM.
    Education is an admirable thing, but it is well to remember from time to time that nothing that is worth knowing can be taught. - Oscar Wilde

  2. #2

    Thread Starter
    Hyperactive Member Maven's Avatar
    Join Date
    Feb 2003
    Location
    Greeneville, TN
    Posts
    322

    Re: tips for optimizing vb code

    lol I didn't know you could only post a max of 10000 charecters =P

    =/ I'm long winded
    Education is an admirable thing, but it is well to remember from time to time that nothing that is worth knowing can be taught. - Oscar Wilde

  3. #3
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,930

    Re: tips for optimizing vb code

    Good stuff

  4. #4
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: tips for optimizing vb code

    I'd complain about this:

    for i = 1 to 50
    strbuffer = strbuffer + b(i)
    next i
    text1.text = strbuffer


    You should use & instead


    Also, it would've been nice if you used [ code ] tags to separate the code. Proper formatting would have been nice, too:

    Code:
    For i = 1 To 50
        strBuffer = strBuffer & b(i)
    Next i
    Text1.Text = strBuffer




    I have some extreme tips here:

    - LenB is faster than Len (though gives result in bytes instead of characters = two times bigger)
    - byte arrays are faster to handle than strings: avoiding string processing gives very good results when we start going to Real Speed with VB6
    - simple math functions in VB are just as fast they are in C++


    Note: I haven't learned ASM as I can do pretty fast code with pure VB. It is only a matter of looking for the fastest things you can do



    Edit More things to the article itself:

    Tip #3 – Avoid dividing if possible.
    A divide instruction is one of the most if not the most expensive instruction you can perform on a CPU. It is faster to multiply then divide!

    B = 40 / 2

    is slower then

    b = 40 * 0.5
    But \ is The Fastest!

    B = 40 \ 2 is faster than doing * 0.5
    Last edited by Merri; Dec 9th, 2004 at 06:45 AM.

  5. #5

    Thread Starter
    Hyperactive Member Maven's Avatar
    Join Date
    Feb 2003
    Location
    Greeneville, TN
    Posts
    322

    Re: tips for optimizing vb code

    Quote Originally Posted by Merri
    I'd complain about this:

    for i = 1 to 50
    strbuffer = strbuffer + b(i)
    next i
    text1.text = strbuffer


    You should use & instead


    Also, it would've been nice if you used [ code ] tags to separate the code. Proper formatting would have been nice, too:

    Code:
    For i = 1 To 50
        strBuffer = strBuffer & b(i)
    Next i
    Text1.Text = strBuffer




    I have some extreme tips here:

    - LenB is faster than Len (though gives result in bytes instead of characters = two times bigger)
    - byte arrays are faster to handle than strings: avoiding string processing gives very good results when we start going to Real Speed with VB6
    - simple math functions in VB are just as fast they are in C++


    Note: I haven't learned ASM as I can do pretty fast code with pure VB. It is only a matter of looking for the fastest things you can do



    Edit More things to the article itself:



    But \ is The Fastest!

    B = 40 \ 2 is faster than doing * 0.5

    I'll format the code after this post.

    No matter what you do really, even optimized code is very slow in visual basic expecially if you compared it to ASM. You don't really have any restrictions in ASM, you can load up 4 charecters of a string in a integer if you want to.

    Multiplication is faster then division on most processors:
    Code:
    Private Declare Function GetTickCount Lib "kernel32" () As Long
    
    Private Sub Command1_Click()
    Dim start As Long
    Dim finish As Long
    Dim i As Long
    Dim b As Long
    
    start = GetTickCount
        For i = 1 To 1000000
            'b = 40 * 0.5
            b = 40 / 2
        Next i
    finish = GetTickCount
    
    Debug.Print (finish - start)
    End Sub
    A division instruction is 50 clock cycles, which is crazy! lol.
    Education is an admirable thing, but it is well to remember from time to time that nothing that is worth knowing can be taught. - Oscar Wilde

  6. #6
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: tips for optimizing vb code

    But \ is still faster, it isn't a division: it just counts how many times the given number fits in the other given number

    I had to make the loop bigger because the values were too small. GetTickCount is getting accurate enough at hundreds. This is tested with uncompiled code:
    / - 750
    * - 560
    \ - 375


    You shouldn't compare ASM and VB. You can do some comparison between C++ and VB. ASM and VB work on so different level of development that you shouldn't compare their speed - VB's strong point is at rapid development, ASM is powerful but very slow to code. Instead, you should concentrate doing VB as fast as you can (when the speed matters). I'm unlikely to touch to ASM at the moment or anytime soon, as VB's optimized speed is enough for my needs - the same goes for many other people, they're unlikely to learn a new language just to make one thing working, say, 10% faster on ASM than what they can get at best with VB (though, many people don't get their code that fast with VB, because speed optimization requires studying and experience a lot).

  7. #7
    New Member
    Join Date
    May 2005
    Posts
    4

    Re: tips for optimizing vb code

    Quote Originally Posted by Maven
    A division instruction is 50 clock cycles, which is crazy! lol.
    On Pentium, but it is faster with newer processors.
    For example, i remember that a division uses 18 clock cycles on AMD K6-2 processors.
    In fact, a multiplication by 0.5 is slower, because it converts the long to a float (moving the data on the stack), then it does the multiplication, and convery the result to long.
    And conversions from integer to float and float to integer are relatively slow.
    I compared the two operations in C++, with MinGW and Borland C++ 5.5.
    And the integer division is about 1.8 times faster with my K6-2 333Mhz processor for MinGW (In fact, with a constant division factor the integer division is optimized like a multiplication by the number inverse, and in that case an integer division by 3 is 5 times faster than the float division).
    An integer division by 2 is even faster, because it uses an arithmetic shift.

    Borland's compiler uses extremely slow code to convert floats to integers (i don't understand why, but that is the case), so it is 5 times slower with float than with integers.

    Conclusion : use float multiplications when variables are floats, and integer division when variables are integers.

  8. #8
    Addicted Member Max_aka_NOBODY's Avatar
    Join Date
    Jul 2004
    Location
    Amman, Jordan
    Posts
    179

    Re: tips for optimizing vb code

    On a completely unrelated note, when facing extreme situations, it makes sense to always use subs rather than functions, and "returning" the value of the function into a variable passed ByRef.

    VB Code:
    1. Private Function sf(ByRef v As Boolean)
    2.  
    3. sf = True
    4.  
    5. End Function
    6.  
    7. '________________________________________
    8.  
    9. Private Sub sf2(ByRef v As Boolean, ByRef dd As Boolean)
    10.  
    11. dd = True
    12.  
    13. End Sub
    14.  
    15. 'sf performs at ~55% of sf2's speed.
    Please, put a checkmark ( ) or the word [RESOLVED] in your topic title if it was resolved, and rate the person who resolved it.

  9. #9
    Addicted Member Max_aka_NOBODY's Avatar
    Join Date
    Jul 2004
    Location
    Amman, Jordan
    Posts
    179

    Re: tips for optimizing vb code

    And IIf is the slowest BTW.
    Please, put a checkmark ( ) or the word [RESOLVED] in your topic title if it was resolved, and rate the person who resolved it.

  10. #10
    Computer Science BS Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,339

    Re: tips for optimizing vb code

    Yup. Also, weren't ElseIf statments faster than Select Case? We proved that in this one thread.

  11. #11
    Admodistrator |2eM!x's Avatar
    Join Date
    Jan 2005
    Posts
    3,900

    Re: tips for optimizing vb code

    i think that was my thread^^

  12. #12
    Hyperactive Member
    Join Date
    Jul 2002
    Location
    WGTN, New Zealand
    Posts
    338

    Re: tips for optimizing vb code

    Quote Originally Posted by Jacob Roman
    Yup. Also, weren't ElseIf statments faster than Select Case? We proved that in this one thread.
    Case:
    VB Code:
    1. Select Case a
    2.  Case 10: MyFunc
    3.  Case 14: YourFunc
    4.  Case 15: Beep 'For arguments sake.
    5. End Select

    If:
    VB Code:
    1. If (a = 10) Then
    2.  MyFunc
    3. ElseIf (a = 14) Then
    4.  YourFunc
    5. ElseIf (a = 15) Then
    6.  Beep
    7. End If

    Keep in mind that an if block really looks like this:
    VB Code:
    1. If (a = 10) Then
    2.  MyFunc
    3.  Goto AfterIfs
    4. End If
    5. If (a = 14) Then
    6.  YourFunc
    7.  Goto AfterIfs
    8. End If
    9. If (a = 15) Then
    10.  Beep
    11. End If
    12. AfterIfs:

    A case statement in ASM looks like this (if it were compiled badly, for arguments sake):

    Code:
    cmp  a, 10        ;compare a with 10
    jne  case2        ;jump if not equal case2
    call MyFunc      ;call MyFunc
    jmp  exitcase     ;exit case
    
    case2:
    cmp  a, 14
    jne  case3
    call YourFunc
    jmp  exitcase
    
    case3:
    cmp  a, 15
    jne  exitcase
    call Beep
    
    exitcase:
    Which looks remarkably like the rewritten if block. I would reckon a good compiler would recognise this and choose only the most efficient ladder, but this is an MS product we are talking about here. Either way, every value is compared (or at least until a match). A good speedup would be to put the most frequent or likely comparison first.

  13. #13
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: tips for optimizing vb code

    Ok, seeing as this is a topic for code optamization.

    Does anyone have any information in using GoTo's?
    I use a few in my code and were wondering how they would affect the code

    Cheers,

    RyaNJ
    My Blog.

    Ryan Jones.

  14. #14

    Thread Starter
    Hyperactive Member Maven's Avatar
    Join Date
    Feb 2003
    Location
    Greeneville, TN
    Posts
    322

    Re: tips for optimizing vb code

    Quote Originally Posted by sciguyryan
    Ok, seeing as this is a topic for code optamization.

    Does anyone have any information in using GoTo's?
    I use a few in my code and were wondering how they would affect the code

    Cheers,

    RyaNJ
    You should never use Gotos in code. It breaks the entire concept of structured programming.
    Education is an admirable thing, but it is well to remember from time to time that nothing that is worth knowing can be taught. - Oscar Wilde

  15. #15
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: tips for optimizing vb code

    Quote Originally Posted by Maven
    You should never use Gotos in code. It breaks the entire concept of structured programming.
    Maven - that wasn't the question!

    With all the constructs available in VB - IF/THEN/ELSE, SELECT/CASE - boolean variables - looping - there are many better ways to flow through logic in VB than to use GOTO.

    As far as speed - I can see no reason why GOTO would be faster than a properly coded IF/THEN/ELSE.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  16. #16
    vbuggy krtxmrtz's Avatar
    Join Date
    May 2002
    Location
    In a probability cloud
    Posts
    5,573

    Re: tips for optimizing vb code

    Quote Originally Posted by szlamany
    With all the constructs available in VB - IF/THEN/ELSE, SELECT/CASE - boolean variables - looping - there are many better ways to flow through logic in VB than to use GOTO.
    Still I've found (actually, very few) situations where a goto was the only way out I could think of. I just can't remember where I stored the specific example I have in mind, but I think it was something having to do with exiting from the innermost nested loop to one of the outer shelling loops.
    Lottery is a tax on people who are bad at maths
    If only mosquitoes sucked fat instead of blood...
    To do is to be (Descartes). To be is to do (Sartre). To be do be do (Sinatra)

  17. #17
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: tips for optimizing vb code

    Quote Originally Posted by krtxmrtz
    Still I've found (actually, very few) situations where a goto was the only way out I could think of. I just can't remember where I stored the specific example I have in mind, but I think it was something having to do with exiting from the innermost nested loop to one of the outer shelling loops.

    Thats exactly my point, it would be much too complex to do with out them (ANd I only use 4 of them dso don't fret )

    I only wanted to know if they would effect the speed of the opperation abd by how much

    I don't think it will have much effect seeing as I only use 4 anyway

    Cheers,

    RyanJ
    My Blog.

    Ryan Jones.

  18. #18
    New Member
    Join Date
    Dec 2005
    Posts
    1

    Re: tips for optimizing vb code

    Quote Originally Posted by krtxmrtz
    Still I've found (actually, very few) situations where a goto was the only way out I could think of. I just can't remember where I stored the specific example I have in mind, but I think it was something having to do with exiting from the innermost nested loop to one of the outer shelling loops.
    I prefer to use Exit's over Goto statements where possible i.e.
    Instead of using this

    Code:
    Public Sub Math(ByRef a as integer)
    Select Case a
       Case 1
         a = a + 1
       Case 2
         b = b + 1
         Goto DoMath
       Case Else
          ' for other numbers
    End Select
    Exit Sub
    
    DoMath: 
    ' The only code that will work past here would be Case 2
    a = a * b
    I would rather use this

    Code:
    Public Sub Math(ByRef a as integer)
    Select Case a
        Case 1
           a = a + 1
           Exit Sub
        Case 2
           b = b + 1
         Case Else
           ' for other numbers
           Exit Sub
    End Select
    
    ' The only code that will work past here would be Case 2
    a = a * b
    End Function
    Thats just me though, sorry for messy code I wrote this in notepad heh

  19. #19
    Computer Science BS Jacob Roman's Avatar
    Join Date
    Aug 2004
    Location
    Miami Beach, FL
    Posts
    5,339

    Re: tips for optimizing vb code

    Goinh back to the subject of slow division, might need some help here Maven:

    Dividing without dividing

  20. #20
    Hyperactive Member
    Join Date
    Apr 2005
    Location
    Indiana
    Posts
    451

    Re: tips for optimizing vb code

    Is

    with form

    .text1.text = a

    end with

    Then same as

    form1.text1.text = a

    ?

  21. #21
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: tips for optimizing vb code

    Quote Originally Posted by Krenshau
    Is

    with form

    .text1.text = a

    end with

    Then same as

    form1.text1.text = a

    ?
    See this thread

    http://www.vbforums.com/showthread.p...highlight=dots

    Especially around post #30...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  22. #22
    Addicted Member
    Join Date
    Aug 2005
    Location
    York
    Posts
    197

    Re: tips for optimizing vb code

    I only wanted to know if they would effect the speed of the opperation abd by how much
    I think he was referring to goto performance wise - goto will perform the same speed as if...then....else or perhaps faster in some cases - its actually just translated to the asm 'jmp' so it doesn't really have performance implications. The main thing most ppl complain about is that its jsut a bad programming practice.
    I tend to disagree with the propaganda from these 'programming practices' but I tend to adhere to them for convenience sake and readability sake. Use Gotos when necessary and don't use them when unnecessary.
    The main case where the goto wins on efficiency is when there is a internal nested loop or something and you need to get out of it - maybe going through two other loops. One way is to use if then and use flags to say the loop is terminated and i want to get out or just use a simple GOTO statment and get out. The latter would be the best approach - because it is faster and is only 1 line of code (and a 2nd line for the label). Other than that you probably manage all with if....then....else.

    The above code with exit subs performance wise should actually be faster because it leaves the sub directly at each branch rather needing to jump.

  23. #23
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: tips for optimizing vb code

    The for loop thing is just a normal behavior for a loop: there is just no point recalculating the value. This also makes for loop faster (= a more efficient choice) than do loop in some situatations.

    I don't see anything wrong with the With statement either, because that's just how it works: With will Reference to class A since C is just a reference to class A; or more so exactly the same as class A. This clarifies why With statement works as it does:

    VB Code:
    1. Option Explicit
    2.  
    3. Private Sub Form_Load()
    4. Dim A As Class1
    5. Dim B As Class1
    6. Dim C As Class1
    7.     Set A = New Class1
    8.     Set B = New Class1
    9.     A.Name = "A"
    10.     B.Name = "B"
    11.     Set C = A
    12.     With C
    13.         Set C = B
    14.         .Name = "1"
    15.         C.Name = "2"
    16.         MsgBox "A: " & A.Name & " - B: " & B.Name
    17.     End With
    18. End Sub

  24. #24
    Fanatic Member alkatran's Avatar
    Join Date
    Apr 2002
    Location
    Canada
    Posts
    860

    Re: tips for optimizing vb code

    Quote Originally Posted by Merri
    The for loop thing is just a normal behavior for a loop: there is just no point recalculating the value. This also makes for loop faster (= a more efficient choice) than do loop in some situatations.

    I don't see anything wrong with the With statement either, because that's just how it works: With will Reference to class A since C is just a reference to class A; or more so exactly the same as class A. This clarifies why With statement works as it does:

    VB Code:
    1. Option Explicit
    2.  
    3. Private Sub Form_Load()
    4. Dim A As Class1
    5. Dim B As Class1
    6. Dim C As Class1
    7.     Set A = New Class1
    8.     Set B = New Class1
    9.     A.Name = "A"
    10.     B.Name = "B"
    11.     Set C = A
    12.     With C
    13.         Set C = B
    14.         .Name = "1"
    15.         C.Name = "2"
    16.         MsgBox "A: " & A.Name & " - B: " & B.Name
    17.     End With
    18. End Sub
    Yes yes, I know that's how it works and appreciate. I was just pointing it out for everyone. I found the With behavior very "huh?!" at first. I thought the compiler was just adding the "c" back in front.
    Don't pay attention to this signature, it's contradictory.

  25. #25
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: tips for optimizing vb code

    Maybe it would be better to point it out in the FAQ forum instead of a thread dedicated for optimization? Atleast that'd make it clear for us to understand you're pointing out something and not wondering it

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