Site Tools

Comparing VBScript Arrays

Developer: RhinoScript
Summary: Discuss efficient VBScript array comparison.


I need to take two collections of items and determine how many of those items had the same name. I am currently using 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

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


Let's say there were 5000 items in arrFirst, 3000 items in arrSecond, and 1500 of them had the same value. Every one of the 3500 unsuccessful searches checked all 3000 arrSecond items, and the 1500 successful searches on average checked 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 was only taking a few microseconds, but all of these calls adds 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
For Each strSecond In arrSecond
  If objLookup.Exists(strSecond) Then intSame = intSame + 1

Which is much, much faster. That's only a couple of thousand function calls. Thus, we at have good reason to believe that this is going to be several times faster.

developer/scriptsamples/arraycompare.txt ยท Last modified: 2015/05/21 (external edit)