Undocumented trick to speed up functions that return array

Undocumented trick to speed up functions that return array

VB6 functions can return an array. Unlike regular functions that return scalar values or objects, however, you can’t use the name of the function as a local variable where to store intermediate result, and you are forced to work with a temporary local array, and then assign this array to the Function name before exiting, as in:

' Returns an array of N random elements' and stores their average in AVGFunction GetRandomArray(ByVal n As Long, avg As Single) As Single()    Dim i As Long, sum As Single    ReDim res(1 To n) As Single    ' fill the array with random values and keep a running total        Randomize Timer    For i = 1 To n        res(i) = Rnd        sum = sum + res(i)    Next    ' assign the result array then evaluate the average    GetRandomArray = res    avg = sum / nEnd Function

Unbelievably, the above routine can be made faster by simply inverting the order of the last two statements, as in:

    ' ...    ' evaluate the average THEN assign the result array     avg = sum / n    GetRandomArray = resEnd Function

For example, on a Pentium II 333MHz machine, when N is 100,000 the former routine runs in 0.72 seconds, while the latter runs in 0.66 seconds, and is therefore 10% faster.

The reason for this odd behavior is that if the former case VB copies the res array into the GetRandomArray result value, and when the array is large this takes a sensible amount of time. In the latter case, the assignment statement is the very last in the procedure, therefore the VB compiler is sure that the temporary res array can’t be used again, and instead of copying it the compiler simply swaps its array descriptor with the descriptor of the GetRandomArray value, thus saving both the physical copy of array elements and the subsequent deallocation of the memory used by the res array.

See also  Redefining Energy Management: Advanced Solutions for Modern Buildings

Summarizing, when writing a Function that returns an array, ensure that the statement that assigns the local array to the return value is immediately followed by a Exit Function or End Function statement (remarks are ignored in this case).


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist