Get Keys()属性对于适当大小的数据集很慢。有没有一种方法可以分配键而不用循环遍历每个记录?
我只能找到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's drop-in Dictionary
replacement交换。
现在,很难看到该类的Dictionary
实现和默认成员(您有那些吗?),但是据我所知,您正在使用[_NewEnum]
循环来迭代对象集合-那就是最慢的迭代任何对象集合的方法。
对象集合想要用For...Next
进行迭代。就是这样,For Each...Next
。
更新could slash the run time by several orders of magnitude UI并运行Application
(甚至每5K迭代运行一次)进一步减慢了循环速度……而且,无论如何,这都不是您想要在DoEvents
成员中进行的事情。
看起来Property Get
是KeyValuePairs
对象的集合?其中的135K意味着很多开销-在.NET中,KeyValuePair
是KeyValuePair
(值类型),而不是struct
(引用类型);它们进行了不同的优化,并且性能也有所不同。无论如何,如果您具有object
对象的集合,则对其进行迭代的最快方法是使用KeyValuePair
循环。
For Each
此外,由于数组在VBA中的工作方式以及与typed数组相关的所有麻烦,我认为returning >>如果将其包装在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
指针中或“返回”会更安全通过Variant
参数(但是对ByRef
成员无效)。