Repository navigation
Passing Data
π A 10,000 x 20 Variant array passed ByVal costs 3.4 ms per call:
VBA copies the whole array every time. ByRef costs 131 ns. Over 100,000 calls
that is about 340 s against 0.01 s. The VBA Performance Manager confirmed
the copy cost (3.5 ms).
' β copies the whole table on every call
Private Function FindRow(ByVal Data As Variant, ByVal Key As String) As Long
' β
passes a reference; the callee only reads the table
Private Function FindRow(ByRef Data As Variant, ByVal Key As String) As LongImportant
In a scan of 18 public VBA projects, 148 ByVal Variant parameters were
indexed as arrays, but only one was a real cost: a lookup helper that received
a whole table ByVal and was called inside a loop. Most were two- or
three-element tuples, where the copy is negligible. The cost needs both a
large array and many calls.
The checker reports this shape as PERF025: HIGH when the procedure walks
the array or indexes it in 2-D and is called inside a loop in the same file,
LOW otherwise (Skill Rules).
π A 100,000-character String passed ByVal: 4.9 us per call, 100x
ByRef.
' β
Private Function CountFields(ByVal Line As String) As Long
' β
when the callee does not change Line
Private Function CountFields(ByRef Line As String) As Long| Trap | Evidence | What to do |
|---|---|---|
A class's Public field passed ByRef
|
π Increment obj.Number left Number at 0: the field is a hidden property pair, so the callee changes a copy |
Copy to a local, pass the local, assign back |
ByVal on an object |
The callee still changes the object's properties: only the reference is copied | Do not rely on ByVal to protect an object |
Switching a ByVal parameter to ByRef
|
The callee may now change the caller's variable | Switch only where the callee does not assign to it |
Dim tmp As Long
tmp = obj.Number
Increment tmp ' ByRef works on the local
obj.Number = tmp| Advice | Result |
|---|---|
| Assign a function's result array as its last statement | π no difference (1%) on 100,000 Double
|
ByVal for a Long or Double
|
No measurable difference either way |
π 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