Site Tools


Comparing VBScript Arrays

Developer: RhinoScript
Summary: Discuss efficient VBScript array comparison.

Question

I need to take two collections of items and determine how many of those items have the same name. I currently use this method for comparison:

intSame = 0
For Each strFirst In arrFirst
  For Each strSecond In arrSecond
    If StrComp(strFirst, strSecond, vbTextCompare) = 0 Then
      intSame = intSame + 1
      Exit For
    End If
  Next
Next

This method, although straightforward, is extremely slow. Is there anything I can do to speed this up?

Answer

Let's say there are 5000 items in arrFirst, 3000 items in arrSecond, and 1500 of them have the same value. Every one of the 3500 unsuccessful searches checks all 3000 arrSecond items, and the 1500 successful searches on average check 1500 arrSecond items each. Each time through, the inner loop does one loop iteration and one string comparison. Add all those up and you get millions of function calls to determine this count. Now, each individual function call is only taking a few microseconds, but all of these calls add up!

Try building a faster lookup table rather than doing a full search through the collection every time.

Set objLookup = CreateObject("Scripting.Dictionary")
For Each strFirst In arrFirst
  Call objLookup.Add(strFirst, 0) ' 0 = some useless value
Next
For Each strSecond In arrSecond
  If objLookup.Exists(strSecond) Then intSame = intSame + 1
Next

This is only a couple of thousand function calls. So we believe that this will be much, much faster.


developer/scriptsamples/arraycompare.txt ยท Last modified: 2015/08/24 by sandy