» Home » VB Fibre
Site
News
Files

Visual Basic
Strings
Math
General
Properties
Memory
Methods

Search
Testing

Inline ASM-VB
Strings
Math
General
Memory

Search
Using inline ASM
Submit!

Declare constant with a type

Such a simple thing can improve performance that much! I've declared a constant as long, and one as variant. Ofcourse you could also use a byte if it fits you more (eg: For packet id's in multiplayer games)

Declarations:
Private Const lngConstant1 As Long = 3.67854 Private Const lngConstant2 = 3.67854

Code:
Public Sub TestOne() Dim lngReturn As Long lngReturn = lngConstant1 * 50 End Sub Public Sub TestTwo() Dim lngReturn As Long lngReturn = lngConstant2 * 50 End Sub

Variant % faster than Long Variant (sec) Long (sec)
486,1% 0,043744 0,007464
505,7% 0,043274 0,007144
605,1% 0,050965 0,007229
497,6% 0,043536 0,007285
743,2% 0,061090 0,007245


User contributed notes:

Author: Rockoon () Date: 20:04 04/04/2004
VB does not treat untyped constant as variants.

Private Const lngConstant1 As Long = 3.67854

...notice the decimal point...

The two operations are completely different. One is doing a single precision multiply by 3.67854 while the other is doing an integer multiply by 4.

If you set both lngConstant's as Long = 3

..you will then see no difference at all between lngConstant1 and lngConstant2.

Author: Almar Joling () Date: 21:04 04/04/2004
I know. I never changed this test though, I always forget to do so. :)

Author: Spodi () Date: 23:02 10/02/2007
Good eye, Rockoon!

It is often still better to get in the practice of declaring your constant types, since VB doesn't always tag them the best they should be.

Author: mpp () Date: 10:06 09/06/2018
1. Create a Module and call it modVariables.bas.
2. Make sure to use the Option Explicit statement.
3. Declare all your Variables as Public in here and save the Module.
4. Create a Module and call it modProcedures.bas.
5. Make sure to use the Option Explicit statement.
6. Put your Subroutines and Functions in here and make sure they are declared as Public.
7. Save the Module.

DO NOT declare your variables within subroutines and functions, and then call those subroutines or functions thousands of times.

Visual Basic will either:
- declare those variables thousands of times
- declare them once and then have to ignore them thousands of times.

Either way you are causing WAY too much overhead for Visual Basic. Just declare them ONCE as Public variables in a module. Simple!

This will also speed up your code above BTW!

Enjoy!
mpp

Add user-note
Author:
E-mail (optional):
Anti spam, please enter 'ok' without quotes:
Comment: