Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Simple variables are always faster than array elements
[ All Languages » VB »  Arrays]

Total Hit ( 2683)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Reading and writing an item of an array is always slower than accessing a simple variable. Therefore, if you need to repeatedly use the same array item in a loop, you should assign it to a temporary variable and use that variable instead. I've included an example of this technique that scans an Integer arrays to see if there are any duplicate values:

Click here to copy the following block
Function AnyDuplicates(intArray() As Integer) As Boolean
  ' returns True if the array holds duplicate values
  Dim i As Long, j As Long,
  Dim lastItem As Long
  Dim value As Integer

  ' evaluate UBound() just once
  lastItem = UBound(intArray)
  For i = LBound(intArray) To lastItem
    ' storing intArray(i) into a non-array variable
    ' saves an indexing operation within the inner loop
    value = intArray(i)
    For j = i + 1 To lastItem
      If value = intArray(j) Then
        AnyDuplicates = True
        Exit Function
      End If
    Next
  Next
  ' no duplicates were found
  AnyDuplicates = False
End Function

The routine is based upon two nested loops and saves CPU time by caching the value of intArray(i) into a regular, non-array variable. This simple trick makes the routine up to 80 percent faster.



Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.