tips for optimizing vb code-VBForums
Page 1 of 2 12 LastLast
Results 1 to 40 of 77

Thread: tips for optimizing vb code

  1. #1

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

    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 11:06 AM.
    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
    321

    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
    37,116

    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 05:45 AM.

  5. #5

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

    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

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

    Re: tips for optimizing vb code

    Quote Originally Posted by Merri
    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).
    If your going to compare languages just for the sake of it, it would be more fair to visual basic if you compared it with delphi then C++.

    You do asm to speed things up more then anything. You don't do entire applications in ASM, just critical areas that must have speed. If you don't do this then you will always be limited to what you can do with visual basic. The gap between asm and visual basic is a lot more then 10%, its more like 90% at least.
    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

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

    Re: tips for optimizing vb code

    Depends what you're doing. For example, doing a highly efficient 3D-engine in ASM would be superb, it would work even on a lower class machine and doing similar with C/C++, Delphi or VB would be hard for the least. The only thing in the way is the development time. But on the topic, this would be a lot faster.

    For simple math processing, you can't do much better than what the basic commands do. 1 + 1 is fast whatever language you use, even though ASM has its own way on it. You can do things in the best possible way in ASM, but it gets maybe too detailed for a "normal" programmer. ASM is a solution, but only for rare, special cases.


    We could try doing something simple as fast as possible with each language to see the real differences.

  9. #9
    Fanatic Member Comintern's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln, NE
    Posts
    826

    Re: tips for optimizing vb code

    OK, here's one I've never seen before. From the speed tests I've been running, it seems to cost a lot of speed to use the built-in VB date functions when working with times. These two code snippets are functionally the same, and Format() returns correctly when passed the double.

    VB Code:
    1. Public Const cYEAR = 365.25
    2. Public Const cDAY = 1
    3. Public Const cHOUR = 1 / 24
    4. Public Const cMINUTE = cHOUR / 60
    5. Public Const cSECOND = cMINUTE / 60
    6.  
    7. Dim dDouble As Double
    8.  
    9. dDouble = Now + (cSECOND * 123)

    The code above is about 5 times faster than the code below:

    VB Code:
    1. Dim dDate As Date
    2.  
    3. dDate = DateAdd("s", 123, Now)

    Even when wrapped in a function like this, the overhead for calling the function is only accounting for about a 20% loss.

    VB Code:
    1. Private Function SecondAdd(dDouble As Double, iSeconds As Integer) As Double
    2.  
    3. SecondAdd = dDouble + (iSeconds * cSECOND)
    4.  
    5. End Function

    The only one that is kind of tricky is the year (because of leap years), but it seems to work to multiply by 365.25 and only keep the integer.

    VB Code:
    1. dDouble = Now + CInt(cYEAR * 12)

  10. #10
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,191

    Re: tips for optimizing vb code

    Quote Originally Posted by Merri
    Depends what you're doing. For example, doing a highly efficient 3D-engine in ASM would be superb, it would work even on a lower class machine and doing similar with C/C++, Delphi or VB would be hard for the least. The only thing in the way is the development time. But on the topic, this would be a lot faster.

    For simple math processing, you can't do much better than what the basic commands do. 1 + 1 is fast whatever language you use, even though ASM has its own way on it. You can do things in the best possible way in ASM, but it gets maybe too detailed for a "normal" programmer. ASM is a solution, but only for rare, special cases.


    We could try doing something simple as fast as possible with each language to see the real differences.

    The point is that in a lower level langauge you can use diffrent instruction set that VB don't use. Like for caluclations and multimedia you can use SSE, SSE2, and MMX instructions that VB never will use.

  11. #11
    Frenzied Member tr333's Avatar
    Join Date
    Nov 2004
    Location
    /dev/st0
    Posts
    1,505

    Re: tips for optimizing vb code

    Tip # 7 – Use long or integer for calculations.
    A long is a 32 bit number and is more natural on 32 bit processors
    A long is a 64 bit number.
    CSS layout comes in to the 21st century with flexbox!
    Just another Perl hacker,

  12. #12

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

    Re: tips for optimizing vb code

    Quote Originally Posted by tr333
    A long is a 64 bit number.
    Long is 32 bit with one exception. When you run .net on a 64 bit platform it will be 64.
    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

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

    Re: tips for optimizing vb code

    Quote Originally Posted by NoteMe
    The point is that in a lower level langauge you can use diffrent instruction set that VB don't use. Like for caluclations and multimedia you can use SSE, SSE2, and MMX instructions that VB never will use.
    Which also means you're limiting the number of computers the code will work on. Of course you could make different code for different instruction sets, but that might require a lot of extra coding... worth it if you're doing something like video and sound manipulation, but near useless if it is for a game loop. Huge time consuming calculations are also something not done by everybody. To have a reason to spend time to code with lower level language such as ASM, you really need to think if it is worth the time spent to the coding, because it does take a lot of time.

    The point you said doesn't change the situatation much at all: low level language stays a something for rare special occasions. If it was more worth the time, more people would be using it often.

  14. #14
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,191

    Re: tips for optimizing vb code

    Quote Originally Posted by Merri
    Which also means you're limiting the number of computers the code will work on. Of course you could make different code for different instruction sets, but that might require a lot of extra coding... worth it if you're doing something like video and sound manipulation, but near useless if it is for a game loop. Huge time consuming calculations are also something not done by everybody. To have a reason to spend time to code with lower level language such as ASM, you really need to think if it is worth the time spent to the coding, because it does take a lot of time.

    The point you said doesn't change the situatation much at all: low level language stays a something for rare special occasions. If it was more worth the time, more people would be using it often.

    All games are using it......even books on DX and OGL. And even dumb me is using it when programming games...

  15. #15
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    15,747

    Re: tips for optimizing vb code

    Quote Originally Posted by Maven
    Long is 32 bit with one exception. When you run .net on a 64 bit platform it will be 64.
    This is absurd - leave it to MS to create a new datatype - SHORT - then reassign INTEGER (which isn't even a datatype!) to 16 bit and LONG to 64 bit.

    DEC had it right - and simple. BYTE was 8, WORD was 16, LONG was 32 and when they created there 64-bit architecture we got QUADWORDS.

    What's MS going to do when 128-bit chips are out?

  16. #16
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,191

    Re: tips for optimizing vb code

    OctWord?

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

    Re: tips for optimizing vb code

    8-bit: BITS
    16-bit: BYTES
    32-bit: SHORT
    64-bit: INTEGER
    128-bit: LONG
    256-bit: HEAVY
    512-bit: DECIMAL
    1024-bit: VARIANT
    2048-bit: XXXL

    This is the future.

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

    Re: tips for optimizing vb code

    Quote Originally Posted by Merri
    8-bit: BITS
    16-bit: BYTES
    32-bit: SHORT
    64-bit: INTEGER
    128-bit: LONG
    256-bit: HEAVY
    512-bit: DECIMAL
    1024-bit: VARIANT
    2048-bit: XXXL

    This is the future.
    Bill should have just asked you in the first place - you have true vision

  19. #19

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

    Re: tips for optimizing vb code

    Quote Originally Posted by szlamany
    Bill should have just asked you in the first place - you have true vision
    BYTE
    WORD
    DWORD
    QUADWORD
    TENBYTE
    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

  20. #20
    Banned timeshifter's Avatar
    Join Date
    Mar 2004
    Location
    at my desk
    Posts
    2,467

    Re: tips for optimizing vb code

    8-bit: BITS
    16-bit: BYTES
    32-bit: SHORT
    64-bit: INTEGER
    128-bit: LONG
    256-bit: VERYLONG
    512-bit: VERYVERYLONG
    1024-bit: SEPTBIT
    2048-bit: OCTBIT

    ...continue as you see fit. Personally, I think we should move into:

    8192-bit: VERYVERYVERYVERYLONG

    There's your future.

  21. #21

    Re: tips for optimizing vb code

    how can you call 8 bit 1 bit.... lol

  22. #22
    New Member
    Join Date
    Jul 2003
    Location
    Wichita, KS
    Posts
    4

    Re: tips for optimizing vb code

    Quote Originally Posted by nareth
    how can you call 8 bit 1 bit.... lol
    He didnt, he called it "BITS"

    Plural
    There are 10 types of people out there: Those who know binary and those that dont.

  23. #23
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: tips for optimizing vb code

    I'm curious why would division be slower than all the other arithmetic operations...and, is this only in vb.net, or does this apply to every language?

    Also, what would you do if you were creating a calculator?

  24. #24
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,191

    Re: tips for optimizing vb code

    Quote Originally Posted by System_Error
    I'm curious why would division be slower than all the other arithmetic operations...and, is this only in vb.net, or does this apply to every language?
    That depends on what instruction codes you can write for in that language. And it also depends on what kind of datatype you are using.

    Quote Originally Posted by System_Error
    Also, what would you do if you were creating a calculator?

    I have seen your work in the Java section. Good stuff, keep it up.

    Well it will depend on what you want to do. If speed is the ultimate goal you will do it the fast way, but not always the most accurate way. If you want the accuracy but don't care that much for the speed, then you will do the most accurate way, and not care about the speed.


    In a calculator you often want it accutate, and don't care if it takes a few ms more then the other way (that even might be more error prone). So if you need Sqrt() or / in your calculator, you will often use that, and not some fancy Carmack code to get the job done.


    Hope that helped.
    ØØ

  25. #25

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

    Re: tips for optimizing vb code

    Quote Originally Posted by System_Error
    I'm curious why would division be slower than all the other arithmetic operations...and, is this only in vb.net, or does this apply to every language?

    Also, what would you do if you were creating a calculator?
    It's slower in every language, not just VB. The reason it's slower is because there is a lot of steps to do when doing division. Basically intel and amd wrote the best general division algorithm they could come up with. You can beat it, but not in all cases. You can always go download the intel docs from their site and see their algorithm for the division instruction. Just know those docs may be a little over-head of some visual basic programmers.

    If you have bitwise operators in a language, it's faster to use them for divison and multiplicaiton where you can. Like shift right 1, is divide by 2. I'm thinking vb.net does but i"m not for sure.

    Loop Unrooling is another thing that apply's to all languages. In fact you're likely to get a better speed up in other languages like C++ and java then visual basic using that trick.

    --------

    I wouldn't think you would need to worry about optimizing a calcualtor. Then again if you're doing some kind of scientific calcualtor, it may be worth the time. The only time I really worry about a divison instruction is when it is inside a loop. I do my best to move it outside a loop. Loops are really what you want to pay special attention to in any language. A divison instruction inside a loop will burn you're speed up fast. Most of the time, it takes more time to execute that one divsion instruction then the rest of the code in a loop. A lot of compare statements in a loop is something I go after too. Like a very long switch statement (Select case in vb doh). I normally go to asm when I have a very long switch because there is some cool tricks in asm you can do that you simply cannot do in any other langauge. I can compare a charecter with every charecter in the ascii set with 1 compare statement in asm where it would take around 255 in any other langauge.

    Before someone asks how that is possible...
    Basically I create what is called a JUMP table. I create all the labels I need and store the offsets in a variable. I then basically offset that variable with what ever number I'm given to search for and then jump to the offset stored in that location in memory. So basically, it's looks at a memroy address for a pointer to the code required to execute that certain event and jump to it.
    Last edited by Maven; Feb 15th, 2005 at 03:43 AM.
    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

  26. #26
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: tips for optimizing vb code

    Thank you Maven and NoteMe, preciate the feedback!

  27. #27
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Candon City, Ilocos Sur, Phils.
    Posts
    10,799

    Re: tips for optimizing vb code

    Isnt

    VB Code:
    1. For i = 1 To ...
    2.     ...
    3. Next

    faster than

    VB Code:
    1. For i = 1 To ...
    2.    ...
    3. Next i

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

    Re: tips for optimizing vb code

    No difference at all. Such things do not matter because the code gets compiled and the variable is "added" there by compiler when it processes the code.

  29. #29
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Candon City, Ilocos Sur, Phils.
    Posts
    10,799

    Re: tips for optimizing vb code

    Is this code
    Code:
    Dim x as integer,a as integer
    x=listbox.count-1
    for a= 0 to x
    next a
    faster than

    Code:
    Dim a as integer
    for a= 0 to listbox.count-1
    next a

  30. #30
    Banned dglienna's Avatar
    Join Date
    Jun 2004
    Location
    Center of it all
    Posts
    17,901

    Re: tips for optimizing vb code

    yes, because the value would have to be calculated for each iteration of the loop in the second instance, which takes time.

  31. #31

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

    Re: tips for optimizing vb code

    Quote Originally Posted by dglienna
    yes, because the value would have to be calculated for each iteration of the loop in the second instance, which takes time.
    Not to mention you'd be using a function call with each iteration of a loop. Every single dot you use, is a call. So more dots, more time.
    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

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

    Re: tips for optimizing vb code

    Actually, that is untrue there: for loops can be and are optimized in this case, because they know how much to do: the values given are "static". It doesn't recount the value in each iteration. If you used a Do... Loop, then there would be a check each time. Do Loop is generally faster than For Next, except in this particular case when using a "static" value. If you need to do from A to B, use For Loop. For anything else Do Loop is likely to be faster.

  33. #33
    Noodly Appendage wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,672

    Re: tips for optimizing vb code

    Quote Originally Posted by Merri
    Actually, that is untrue there: for loops can be and are optimized in this case, because they know how much to do: the values given are "static". It doesn't recount the value in each iteration. If you used a Do... Loop, then there would be a check each time. Do Loop is generally faster than For Next, except in this particular case when using a "static" value. If you need to do from A to B, use For Loop. For anything else Do Loop is likely to be faster.
    MSDN says there is no significant difference between Do and For.
    I don't live here any more.

  34. #34
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Candon City, Ilocos Sur, Phils.
    Posts
    10,799

    Re: tips for optimizing vb code

    Unless disproved by others I believe these would also optimize vb code

    using chr$ over chr
    using mid$ over mid
    using left$ over left
    using right$ over right
    etc....

    using textbox = 'your text' over textbox.text = 'your text'
    using label = 'your caption' over label.caption = 'your caption'
    etc....

    using textbox = vbnullstring over textbox = ""
    using label = vbnullstring over label = ""
    etc....

    using command_click over command.value = true
    etc....
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  35. #35
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    CT
    Posts
    15,747

    Re: tips for optimizing vb code

    I agree - but they really fall into the realm of best practices.

    What you have can be summed up with:

    1) Do not use VARIANT datatypes when other datatypes are appropriate.
    2) Do not use FUNCTIONS that return VARIANT datatypes.
    3) Use CONSTANTS (self-declared or VB standard) instead of literal values when possible.

    I'm not sure everyone would agree with use TEXTBOX = instead of TEXTBOX.TEXT = . In general, it is not a best practice to use DEFAULT PROPERTIES.

    *** 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

  36. #36
    Banned plenderj's Avatar
    Join Date
    Jan 2001
    Location
    Dublin, Ireland
    Posts
    10,359

    Re: tips for optimizing vb code

    Quote Originally Posted by dee-u
    using chr$ over chr
    using mid$ over mid
    using left$ over left
    using right$ over right
    Correct as they return Variants by default, whereas appending the dollar sign will cause it to return a String.

    Quote Originally Posted by dee-u
    using textbox = 'your text' over textbox.text = 'your text'
    using label = 'your caption' over label.caption = 'your caption'
    I don't agree. I think its bad coding practice to make use of defauly properties.
    Looks nicer sometimes though

    Quote Originally Posted by dee-u
    using textbox = vbnullstring over textbox = ""
    using label = vbnullstring over label = ""
    etc....
    I would agree.

  37. #37
    Noodly Appendage wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,672

    Re: tips for optimizing vb code

    Quote Originally Posted by plenderj
    I don't agree. I think its bad coding practice to make use of defauly properties.
    In VB6 I would also agree on this point. But it it not the case with VB.Net, which has Default properties and tight rules about their use. They generally tend to be a wrapper for some internal array or function or something like that. They can be extremely useful and in many cases it is quite obvious that a default property is being used.

    Just thought I'd add that in case any VB6-->.Net newbies get into the habit of disliking default properties and bring that belief with them to .net
    Last edited by wossname; Mar 14th, 2005 at 07:39 AM.
    I don't live here any more.

  38. #38
    Banned plenderj's Avatar
    Join Date
    Jan 2001
    Location
    Dublin, Ireland
    Posts
    10,359

    Re: tips for optimizing vb code

    Oh don't be so arrogant

  39. #39
    Noodly Appendage wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,672

    Re: tips for optimizing vb code

    My middle name is Supercillious.
    I don't live here any more.

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

    Re: tips for optimizing vb code

    Here you have some VB6 code that shows For ... Next is slower than Do ... Loop. Both do as equal amount of work within the loop as possible:

    VB Code:
    1. 'For ... Next
    2.     For A = 1 To Iterations
    3.         A = A
    4.     Next A
    5. 'Do ... Loop
    6.     A = 1
    7.     Do While A < Iterations
    8.         A = A + 1
    9.     Loop

    Doing 1 000 000 000 iterations results ~1550 ms vs. ~1030 ms on my machine.

    And the full source...
    Attached Files Attached Files

Page 1 of 2 12 LastLast

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.