Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Aug 15, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Improve Performance by Eliminating Subexpression

Arrays can reduce the amount of code you must write to perform an operation, especially when used with a loop. By using the same array element in multiple places in your code, you can increase the speed with which your code executes if you resolve the array only once. This code determines if the value of the array element is this value, or if the value of the array element is that value:

 If intArray(intArrayIndex) = 5 or _
	intArray(intArrayIndex) = 10 Then

Because Visual Basic must calculate the location of the array element to resolve its value (base + intArrayIndex * sizeof_intArray_type), it makes sense that the code executes faster the less the calculation is performed. This code provides a faster implementation:

 TheValue = intArray(intArrayIndex)
If TheValue = 5 or TheValue = 10 Then

This technique offers performance gains that are even more dramatic when used in a loop:

 For intArrayIndex = 0 to 10
TheValue = intArray(intArrayIndex)
If TheValue = 5 or TheValue = 10 Then
	' Do something here
End If

By eliminating the redundant subexpression and assigning the value to the variable named "TheValue" only once per loop (executes 10 times) instead of twice per loop (executes 20 times), you significantly reduce the amount of work that VB must perform to complete this loop.

Charles Caison
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date