This document is an tip from the Advisor via an email tip link from SearchDomino's email tips.
By Ted Sadler
Durham, NC, US
The tip you sent out recently on this was terribly inefficient because of the nested loop and especially the use of redim preserve. I compared that with the code below sorting a list of 500 random strings and repeating this 100 times. The original code took 37 seconds. This code took 3 seconds...
(new code based on original. couple minor adjustments have been made)
Function LSUnique(vIn As Variant) As Variant
Dim lsTemp List As String ' Create the list
Dim astemp() As String ' A place to store the compacted array
Dim iCount As Integer ' Count how many uniques we find
' Make sure they sent us an array of strings
If Not Isarray(vIn) Then
Print "(Unique) Unique requires an array as input"
LSUnique = vIn
Exit Function
Elseif Typename( vIn(0) ) <> "STRING" Then
Print "(Unique) Unique requires an array of strings as input. vIn(0) is a " _
+ Typename( vIn(0) )
LSUnique = vIn
Exit Function
End If
Forall s In vIn
' If the entry isn't in the list...
If Not Iselement( lsTemp(s) ) Then
' Add it to the list
' Note that we don't care what's in the list; we just want the list tag
lsTemp(s) = ""
iCount = iCount + 1
End If
End Forall
' Note that there's no "preserve" keyword here so this is relatively quick
Redim asTemp(iCount-1)
iCount = 0
' Copy all the unique elements into the temp array
Forall v In lsTemp
asTemp(iCount) = Listtag(v)
iCount = iCount + 1
End Forall
' Return the temp array
LSUnique = asTemp
End Function
previous page
|