Valhalla Legends Forums Archive | General Programming | VB Code Optimizations

AuthorMessageTime
Noodlez
I read this article on planet source code and thought people here would benefit from it.
[quote]
Optimizations
Copyright © 2003 by Paul Guerra. E-mail: gusdama@yahoo.com

We always want our programs to run faster and be as small as possible. But sometimes it is not worth it to change the whole source code just to make it a few miliseconds faster.
If the program does not perform any "hard" loop, you shouldn't optimize it. But if your program is an encryptor, for example, you should make everything to make it faster.

The best way to optimize a program is changing its main algorithm. But if you are too lazy (or have already done it), try the following:

·      Remove variant variables
     
     Variant variables are very flexible. They let you store whatever value you want. But the cost of this flexibility is not low: they are slooooooow. So never ever use the variant data type. Be careful with this kind of mistake:
     
     Dim var1, var2, var3 as Integer
     
     Some people think that with this piece of code you declare 3 integer variables. Unless you included a Deftype statement, you are actually declaring 1 integer and 2 variant variables. The correct way to do this is:
     
     Dim var1 as Integer, var2 as Integer, var3 as Integer
     
·      Use Option Explicit
     
     VB lets you use variables that aren’t actually declared. This kind of variables are called implicit variables, and by default VB declares them internally as variant variables (unless of course you included a Deftype statement).
     Every time VB encounters an unknown identifier, automatically declares that variable as a slow, implicit, variant variable, and doesn’t show any error, unless you are using the Option Explicit statement. This tells VB to force variable declaration, and will help you reduce bugs in programs and improve programs speed.
     
·      Use Longs
     
     If you need to store integer numbers, you should use the long data type. It is the fastest integer data type for 32-bits processors. Some people think it requires more memory, and that’s sometimes true. But if you use a local byte variable, for example, VB allocates a double word (i.e. 4 bytes) in the stack, just like a long variable. This is because local data in stack is supposed to be located at a dword boundary.
     
·      Avoid using floating-point operations
     
     Floating-point types (single and double data types) and operations where a floating-point number is returned, are much slower than integer-type operations. So if you need to do this:
     
     Dim var1 as Long
     ...
     var1 = 8 * 2 / 6
     
     Do it this way:
     
     Dim var1 as Long
     ...
     var1 = 8 * 2 \ 6
     
·      Use multiplication instead of division
     
     If you need to perform a floating-point divition, it is sometimes faster to transform it in a multiplication. For example:
     
     Dim var1 as Single
     ...
     var1 = 559 / 2
     
     Is slower than:
     
     Dim var1 as Single
     ...
     var1 = 559 * 0.5
     
·      Eliminate parenthesis
     
     Sometimes eliminating parenthesis may increase the speed of an expression. In the following case:
     
     var1 = 8 * (5 + 2)
     
     Is slower than:
     
     var1 = 8 * 5 + 8 * 2
     
·      Simplificate expressions
     
     Some complex expressions can be simplified. By doing this, you ensure the maximum speed. Take this expression as an example:
     
     var1 = 9 * (var2 + 6 / 3) - 5
     
     You know the result of 6 / 3, so you can simplify it:
     
     var1 = 9 * (var2 + 2) - 5
     
     Applying the rule of eliminating parenthesis, you get:
     
     var1 = 9 * var2 + 9 * 2 - 5
     
     Again, you can simplify it:
     
     var1 = 9 * var2 + 13
     
     See? Now the expression is much smaller (and faster).
     
·      Be careful of strings
     
     The string data type holds text. It is very useful. But it is one of the slowest data type. When using it, you should pay attention to stuff like this:
     
     To test if a string is not emtpy, most people do this:
     
     If StrVar <> "" Then
     
     But this can be optimized. Check this out:
     
     If Len(StrVar) Then
     
     Testing the length of a string is faster than testing its content.
     
     There are some string functions that may return variant values too. For example, the Chr$() function returns an ASCII character based on the value of its argument. But some people use the Chr() funcion, which is the same as Chr$() but it returns a variant.
     
     If you have to do this:
     
     var1 = Chr(var2)
     
     Do it this way:
     
     var1 = Chr$(var2)
     
·      Use the 'With' statement
     
     When accessing an object, specially those arrays of complex user-defined types, VB must evaluate the whole object before you can actually access it.
     If you must use this kind of object repeteadly, it may turn out in a very low-performance code.
     The 'With' statement lets you evaluate this objects only once and then access them all the times you want.
     An example should clear the idea:
     
     Type ChildInfo
           Name As String
           Age As Long
           Male As Boolean
     End Type
     Type Person
           Name As String
           Age As Long
           Male As Boolean
           Children() As ChildInfo
     End Type
     Dim Parents(10) As Person
     
     This code is not very good:
     
     Parent(3).Name = "Peter"
     Parent(3).Children(4).Name = "John"
     Parent(3).Age = 36
     
     But this one is better:
     
     With Parent(3)
           .Name = "Peter"
           .Children(4).Name = "John"
           .Age = 36
     End With
     
·      Avoid Methods
     
     Methods are slower than regular procedures. They have extra code that is not generated for regular procedures. The problem is that all of us use methods without knowing they&#8217;re actually methods.
     But what is a method anyway? A method is a procedure (you know what a procedure is, right?) in a class. And keep in mind that forms are classes, too. So each time you declare a Sub or a Function in a form, you are declaring a method. To improve speed, move as many procedures as possible to a module.
     
·      Use Select Case
     
     The Select Case statement executes very fast when compiled to native code if the test expression is an integer type expression. Otherwise it is as fast as using many if&#8217;s.
     If the test expression is of an integer type VB uses a switch table, avoiding comparisons. This improves speed and size.
     
·      ByVal instead of ByRef
     
     ByVal is much faster than ByRef, and I&#8217;ll tell you why. Consider the following piece of code:
     
     Function Add(Num1 As Long, Num2 As Long) As Long
       Add = Num1 + Num2
     End Function
     
     Result = Add(5, 9)
     
     In the last line you call the function, and pass the numbers 5 and 9. But since the parameters are ByRef, the function is expecting two variables, NOT two numbers. So what happens here? Do you think VB just pushes those numbers to the stack and calls the function? No!!!!! In this case the function would CRASH because it will think the variables are located at addresses 5 and 9 in memory, and this is wrong.
     The real thing is that VB creates two temporal local variables, loads these variables with the numbers 5 and 9, and passes these temporal variables to the function. Now this is slow, except in the case of string parameters, since it is actually faster to create these temporal variables than copying the whole string every time you want to call the function.
     So what I&#8217;m trying to say here is that you should use always ByVal instead of ByRef, except for string parameters.
     
·      Simplificate Boolean expressions
     
     Boolean expressions return either True or False. They are used in logical decisions. Although boolean expressions may be simplified using boolean algebra, most people are not interested in it (you can e-mail me to get information on boolean algebra). But you can still optimize it.
     For example:
     
     If <condition> Then
           BoolVar = True
     Else
           BoolVar = False
     EndIf
     
     That is not very bright. You can do it in just one line:
     
     BoolVar = <condition>
     
·      Optimize If&#8217;s

If you have two or more nested If statements, you should put first the If statement with most chances to be false. So if it is false, VB won't have to evaluate other conditions.
[/quote]
February 4, 2003, 10:47 PM
iago
And the best way of all

drumroll......

Don't use Visual Basic! ^^

But seriously, those are good suggestions.. at least, up to where I read to :)
February 4, 2003, 11:55 PM
Yoni
Randomly read in the middle...

[quote]Now this is slow, except in the case of string parameters, since it is actually faster to create these temporal variables than copying the whole string every time you want to call the function[/quote]

I think the author is confused.
February 5, 2003, 12:03 AM
Arta
Iago stop stealing my jokes (biatch) :P
February 7, 2003, 9:56 AM
St0rm.iD
Delphi is leet
Java is leeter
Jython is leetest

C is wicked fuckin cool too

C++ blows

Objective-C is odd.
February 7, 2003, 8:28 PM
iago
How can you like Java and now C++?

Anyway, C++ > C if you use it right; I hate not having overloading, and I like to use classes occasionally (although overuse is never good).
February 8, 2003, 4:52 AM
St0rm.iD
I dunno, C++ just doesn't seem clean, it seems like a hack. Sort of like, it's trying to abstract a lot of stuff away using OOP but it needs to keep pointers and stuff because of backward compatibility and performance.

However, I think C and ASM are orgasmic ;)
February 8, 2003, 10:04 AM
Skywing
[quote]I dunno, C++ just doesn't seem clean, it seems like a hack. Sort of like, it's trying to abstract a lot of stuff away using OOP but it needs to keep pointers and stuff because of backward compatibility and performance.

However, I think C and ASM are orgasmic ;)[/quote]I see.  And this is why the vast majority of programs out there are written in C++?
February 8, 2003, 5:06 PM
Eibro
[quote]I dunno, C++ just doesn't seem clean, it seems like a hack. Sort of like, it's trying to abstract a lot of stuff away using OOP but it needs to keep pointers and stuff because of backward compatibility and performance.

However, I think C and ASM are orgasmic ;)[/quote]
Why even begin to judge something you don't understand? From what I can gather, you're saying you know nothing about C++.
February 8, 2003, 6:24 PM
St0rm.iD
Uhhh...yes I do know C++.

It was just a fuckin opinion. Don't start shit shithead.
February 9, 2003, 8:09 PM
Zakath
It *is* a bit difficult to know anything about Java and not be able to extend it into C++...the concepts behind much of the stuff are the same (not to mention the syntax). :P
February 10, 2003, 6:34 PM

Search