GetKeys((属性的速度较慢,数据集大小适中。有没有一种方法可以在不单独循环每个记录的情况下分配密钥?
我只能找到for或do循环的例子来单独分配关键点。
Public Property Get Keys() As String()
'Here is the existing code (status bar updated only so the user knows the
'program is still working).
Dim vlist() As String, i As Long, myKey As Variant, myArr() As Variant, okVP As KeyValuePair, StatBar As String
StatBar = Application.StatusBar
If Me.Count > 0 Then
ReDim vlist(0 To Me.Count - 1)
For i = LBound(vlist) To UBound(vlist)
Set okVP = KeyValuePairs(i + 1)
vlist(i) = okVP.Key
If i Mod 5000 = 0 Then
Application.StatusBar = StatBar & ": " & "Gathering Keys: " & Format(i, "#,##0") & " of " & Format(UBound(vlist), "#,##0")
' Debug.Print i & " of " & UBound(vlist)
DoEvents
End If
Next i
Keys = vlist
End If
Application.StatusBar = StatBar
End Property
目前的方法需要5分钟以上才能获得约135K条记录。
不,您无法避免迭代项目。在Windows下,您可能会利用CopyMemory
Win32 API来批量复制数组,但我不相信这些函数能在Mac上工作。
考虑将基于KeyValuePair
的Dictionary
替换为Tim Hall的内置Dictionary
。
现在,如果没有看到类的[_NewEnum]
实现和默认成员(你有这些吗?(,很难判断,但据我所知,你正在用For...Next
循环迭代对象集合,这是迭代任何对象集合的最慢方法。
对象集合希望使用For Each...Next
进行迭代。仅此一点,就可以将运行时间缩短几个数量级。
更新Application
UI并运行DoEvents
(甚至每5K迭代一次(会进一步减缓循环。。。无论如何,这不是你想在Property Get
成员中做的事情。
看起来KeyValuePairs
是KeyValuePair
对象的集合?135K意味着相当多的开销——在.NET中,KeyValuePair
是struct
(值类型(,而不是object
(引用类型(;它们的优化方式不同,性能也不同。无论如何,如果您有一个KeyValuePair
对象的集合,迭代它们的最快方法是使用For Each
循环。
ReDim result(0 To KeyValuePairs.Count - 1)
Dim i As Long
Dim kvp As KeyValuePair
For Each kvp In KeyValuePairs
result(i) = kvp.Key
i = i + 1
Next
此外,由于数组在VBA中的工作方式以及与类型的数组相关的所有头痛问题,我认为返回一个数组如果封装在Variant
指针中或通过ByRef
参数"返回"会更安全(但这对Property Get
成员不起作用(。