Results 1 to 40 of 77

Thread: tips for optimizing vb code

Threaded 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

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