Repository navigation
Searching Sorting and Collections
These costs grow with the size of the data. A loop that takes a tenth of a second on test data can take minutes on production data.
π A linear scan of 100,000 sorted values: 650 us per search. A binary search: 0.6 us. Over 100,000 searches: about 65 s against 0.06 s.
' β
binary search in a sorted typed array; returns 0 when absent
Public Function BinarySearch(ByRef a() As Long, ByVal x As Long) As Long
Dim lo As Long, hi As Long, md As Long
lo = LBound(a): hi = UBound(a)
Do While lo <= hi
md = (lo + hi) \ 2
If a(md) = x Then
BinarySearch = md
Exit Function
ElseIf a(md) < x Then
lo = md + 1
Else
hi = md - 1
End If
Loop
End Functionπ Each col(i) walks the Collection from the start: 27 us per read at
20,000 items, 520x For Each. One pass over 100,000 items: about 13 s
(estimate). The checker reports it as PERF019.
' β quadratic
For i = 1 To col.Count
Total = Total + col(i)
Next i
' β
linear
For Each v In col
Total = Total + v
Next vπ Finding a duplicate in 5,000 values with two loops: 0.12 s, 19x a
Dictionary pass, and growing with the square of the size (about 12 s at
50,000). Copying a(i) to a variable before the inner loop saves only 22%.
' β
one pass
Dim d As Object, i As Long
Set d = CreateObject("Scripting.Dictionary")
For i = LBound(a) To UBound(a)
If d.Exists(a(i)) Then
FirstDuplicateAt = i
Exit For
End If
d.Add a(i), i
Next iπ 100,000 lookups among 100,000 string keys:
| Method | Per lookup | Note |
|---|---|---|
| Hash table written in VBA | 0.72 us | Fastest, but code to write and maintain |
β
Binary search on a sorted String array |
0.76 us | Simple; sort the keys once |
Scripting.Dictionary, early bound |
1.6 us | Needs a reference to Microsoft Scripting Runtime; Add 0.9 us |
Scripting.Dictionary, late bound (As Object) |
2.2-2.9 us |
Add 1.4 us |
Collection key plus On Error
|
2.7 us | Raises an error on every miss |
Tip
For a fixed table looked up many times (a holiday calendar, curve pillars), a
sorted typed array with a binary search is about 2x an early-bound
Dictionary. Use a Dictionary to build sets, group, and remove duplicates.
Sort 50,000 random Double
|
Per element | Ratio |
|---|---|---|
β
QuickSort on Double()
|
0.58 us | 1.0x |
β
One WorksheetFunction.Sort call |
0.66 us | 1.14x |
ShellSort on Double()
|
1.45 us | 2.5x |
ShellSort on a Variant array |
2.55 us | 4.4x |
π Dates (or any integer keys in a narrow range): CountSort is 7x a QuickSort.
' β
CountSort for Long keys such as date serials: linear time
Public Sub CountSortLong(ByRef a() As Long)
Dim i As Long, k As Long, pos As Long, lo As Long, hi As Long, cnt() As Long
lo = a(LBound(a)): hi = lo
For i = LBound(a) To UBound(a)
If a(i) < lo Then
lo = a(i)
ElseIf a(i) > hi Then
hi = a(i)
End If
Next i
ReDim cnt(lo To hi)
For i = LBound(a) To UBound(a)
cnt(a(i)) = cnt(a(i)) + 1
Next i
pos = LBound(a)
For k = lo To hi
For i = 1 To cnt(k)
a(pos) = k
pos = pos + 1
Next i
Next k
End Sub| Task | π Result |
|---|---|
Empty a Collection of 10,000 with Remove from the end |
about 15 us per Remove, 7.7x Remove 1; β
Set col = New Collection costs nothing |
Drop duplicates with Collection plus On Error Resume Next
|
2.2x Dictionary.Exists, and the error trap hides real errors |
Membership through InStr(Join(arr, vbNullChar), ...) per check |
1.2x slower than the plain loop it replaces; a Dictionary built once is 4x faster |
π Run K, keep 2 of every 3 input values in an array that grows (two machines, 64-bit Excel, 1-D arrays):
| Variant | 100,000 Long
|
100,000 String
|
Ratio |
|---|---|---|---|
| β Sized to the input, one trim at the end | 2.2-2.4 ms | 5.7-6.3 ms | 1x |
| β Capacity doubled when full, one trim | 2.5-2.6 ms | 5.9-7.6 ms | 1.0-1.5x |
| Capacity grown by 1,000, one trim | 2.5-2.6 ms | 7.7-8.4 ms | 1.1-1.35x |
A counting pass, one ReDim, then fill |
3.6 ms | 6.9-12.8 ms | 1.2-2x |
β ReDim Preserve for every item |
7.9-11.9 ms | 13.7-42 ms | 2.4-6.7x |
β Collection.Add, then copy into an array |
11.4-12.1 ms | 25-28 ms | 4-6.5x |
- π’
ReDim Preserveper item is not quadratic here: 0.08-0.42 us per item at 10,000 and at 100,000 items, 10-40 ms in all for 100,000. It is worth fixing in hot code, not a top cost. π§ͺ 32-bit Excel and 2-D arrays are not measured. - β A
Collectionis no fix forReDim Preserve: filling one and copying it into an array was the slowest form.
' β
size to an upper bound, trim once
ReDim Kept(1 To n)
For i = 1 To n
If Keep(i) Then
Used = Used + 1
Kept(Used) = Values(i)
End If
Next i
If Used > 0 Then ReDim Preserve Kept(1 To Used)Warning
π ReDim Preserve changes only the upper bound of the last dimension:
changing the first dimension, or the lower bound, raised error 9 and left
the array as it was. Build rows as columns, or one array per column.
| Advice | π Result |
|---|---|
| Loop order over a 2-D array (rows or columns outer) | Within 12% |
RtlZeroMemory to clear part of an array once |
15 ms per million Double with a loop |
π Figures: Excel 365 (16.0 build 20723) 64-bit, Windows desktop, median of 5 runs Β· Raw data in docs/benchmarks/
- π Home
- π Measurement Method
Topics
- π Working with Excel
- π¦ Passing Data
- π€ Strings
- π’ Numbers and Dates
- π Searching, Sorting and Collections
- π§© Calls, Classes and Binding
- π Files and CSV
- πͺ Windows API on 64-bit Office
Reference
β οΈ Correctness Traps- π§° Skill Rules