Wednesday, May 20, 2009

ByRef and ByVal

Something I have recently been trying in my never ending quest to make my code look good is ByRef and ByVal. The standard in VB Script is ByVal, so lets look at a function:
Function AddOneByVal(intNumber)
AddOneByVal = intNumber + 1
End Function

The way that the code really looks like is this:
Function AddOneByVal(ByVal intNumber)
AddOneByVal = intNumber + 1
End Function

ByVal simply means that we are passing the function a value. If we call AddOneByVal(integer), this means that we are sending the value of the variable integer to the function AddOneByVal. If integer equals 5, the function will return 6. Pretty simple stuff.

But now lets look at ByRef:
Function AddOneByRef(ByRef intNumber)
intNumber = intNumber + 1
End Function

Here we are sending the function a reference to a value. If we now call this function using AddOne(integer), with integer again equaling 5, we aren't just sending the value 5 to the function, we are sending the actual variable integer, that currently equals 5. The function will still add one and return 6 as a result.

What's good about that? Mainly (for me) it's easier to handle. Instead of calling the function like this:
intResult = AddOneByVal(intTestByVal)

We can now call the function like this:
AddOneByRef intTestByRef

Another (and better) example would be to call a sorting function like this:
Sort arrList

Instead of:
strListSorted = Sort(arrList)

I have been looking around online for further differences with using ByVal and ByRef, but I haven't really been able to find anything definitive. That said, I would guess that ByRef is slightly faster since you are using the actual variable, and not creating an extra copy of the variable. We also don't need to assign the new value back anything.

No comments: