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
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!
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
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).
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
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.
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:
Public Const cYEAR = 365.25
Public Const cDAY = 1
Public Const cHOUR = 1 / 24
Public Const cMINUTE = cHOUR / 60
Public Const cSECOND = cMINUTE / 60
Dim dDouble As Double
dDouble = Now + (cSECOND * 123)
The code above is about 5 times faster than the code below:
VB Code:
Dim dDate As Date
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:
Private Function SecondAdd(dDouble As Double, iSeconds As Integer) As Double
SecondAdd = dDouble + (iSeconds * cSECOND)
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.
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.
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.
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...
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.
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.
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 04: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
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.
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.
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 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".
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 08:39 AM.