» 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!

Byref returned vs. Function returned

Maybe not everybody knows it, but standardly all arguments passed to a method are ByRef. This means if you change the value of this Variable, it will also change in the calling sub. Using this method you can make subs act like a function. But is it worth it... Well seems not, it's around 40% slower.

Code:
Public Sub TestOne() Dim lngReturn As Long Call Function1(lngReturn) End Sub Public Sub TestTwo() Dim lngReturn As Long lngReturn = Function2 End Sub Private Sub Function1(Answer As Long) Answer = 100 * 55 End Sub Private Function Function2() As Long Function2 = 100 * 55 End Function

Function % faster than Byref Function (sec) Byref (sec)
54,3% 0,095617 0,147544
27,2% 0,104869 0,133398
51,2% 0,093329 0,141092
54,2% 0,096193 0,148360
36,3% 0,097453 0,132801


User contributed notes:

Author: PRoPHEZZoR () Date: 10:08 24/08/2004
Uh... You typed "ByRef % faster than Function" in that last table.
You must be making a joke, it's the other way around ;-)

Author: Almar Joling () Date: 11:08 24/08/2004
fixed.

Author: Comintern () Date: 22:03 15/03/2005
Function calls reserve stack space for a return value, Subs do not.

Author: Tom (hurendo_kun at hotmail dot com) Date: 16:06 08/06/2005
You're passing an argument to the first procedure, which slows it down. So, in this particular case, it's faster to make a function call with no arguments... but you may encounter a case where you need to use the argument in your algorithm and retrieve the result using the same argument, in which case the first method should be faster.

Author: TheShau (shauros at walla dot com) Date: 15:08 04/08/2006
I've tested liek this, which seems more accurate.

Public Sub TestOne()
Dim lngReturn As Long
Call Function1(lngReturn)
End Sub

Public Sub TestTwo()
Dim lngReturn As Long
lngReturn = Function2(lngReturn)
End Sub

Private Function Function1(Answer As Long) As Long
Answer = 100 * 55
End Function

Private Function Function2(Answer As Long) As Long
Function2 = 100 * 55
End Function

The tests produce the same times, except for incidental (1 out of 2 or 3) dramatic drops in run time (around 20-30%) for the byref version.
I can't find a good explanation, but thought I might post it anyway.

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