Excel 字典、集合和数组的比较
我试图找出字典与集合和数组相比的相对优势和特性 我找到了一篇优秀的文章,但找不到一个简单的表格来比较所有不同的特性Excel 字典、集合和数组的比较,excel,vba,ms-access,Excel,Vba,Ms Access,我试图找出字典与集合和数组相比的相对优势和特性 我找到了一篇优秀的文章,但找不到一个简单的表格来比较所有不同的特性 有人知道吗?请参阅下表,以了解收藏和词典的有用比较 (该表总结了“早期和晚期绑定”部分。仅供参考,该页面还提供了有关使用词典的更详细信息) 总之,通常最好使用字典或数组 在考虑使用集合时,如果大小没有变化,或者变化很少,则使用数组可能更合适。在这种情况下,数组可能比集合更高效,因为数组可以非常高效地一次填充和检索所有项(例如,从范围到数组和从数组返回范围) 另请注意: 与数组相比,
有人知道吗?请参阅下表,以了解收藏和词典的有用比较 (该表总结了“早期和晚期绑定”部分。仅供参考,该页面还提供了有关使用词典的更详细信息) 总之,通常最好使用字典或数组 在考虑使用集合时,如果大小没有变化,或者变化很少,则使用数组可能更合适。在这种情况下,数组可能比集合更高效,因为数组可以非常高效地一次填充和检索所有项(例如,从范围到数组和从数组返回范围) 另请注意: 与数组相比,集合在添加和插入项以及通过键访问和删除项方面提供了良好的性能。但是,如果要通过索引访问项,则性能很差。有关有效执行此操作的信息,请参阅其中还讨论了这些列表对象的内部工作方式 has有非常有用的代码用于处理字典、集合和数组(对它们进行排序,并将它们相互转换!) cpearson页面中的一些文本: Collection对象和Dictionary对象对于 存储相关数据组。在其他条件相同的情况下,我使用 字典对象而不是集合对象,因为 访问(读、写、更改)与 词典中的项目。在一个相当糟糕的对象设计中,一个 集合中的项为“仅写”。您可以为项目分配密钥 将项添加到集合中,但无法检索 与项目关联的键,也不能(直接)确定 密钥存在于集合中。字典非常友好和开放 用他们的钥匙。词典的速度也大大快于计算机 收藏 为什么阵列是一个糟糕的选择。 当Redim将整个内存块复制到更大的位置时,数组在重新调整大小和插入中间项目时要慢得多,并且如果使用保留,所有值也会被复制。这可能会转化为每个操作的感知缓慢(在潜在应用中) VBA中的集合与词典
Feature | COLLECTION | DICTIONARY | Remark
------------------------+------------+------------+--------------------------------
Usually faster | | X |
------------------------+------------+------------+--------------------------------
Supported by VB Script | | X | Collections do not exist in VBS.
------------------------+------------+------------+--------------------------------
| | | Dicts: Add ref to Miscrosoft
Native to VBA | X | | Scripting Library. Usage:
| | | Dim MyDict As Scripting.Dictionary
| | | Set MyDict = New Scripting.Dictionary
------------------------+------------+------------+--------------------------------
Can change Keys and | | | Dict properties are writable.
Items | | X | For collections, remove the item
| | | and add a new item.
------------------------+------------+------------+--------------------------------
| | | A collection enumerates its items:
| | | For Each x In MyCollection
| | | Debug.Print x
Enumerated | X | X | Next x
| | | A dict enumerates its keys:
| | | For Each x In MyDictionary
| | | Debug.Print MyDictionary.Item(x)
| | | Next x
------------------------+------------+------------+--------------------------------
| | | A 1-d array of keys
Directly output to | | | and items can be returned by
array | | X | dict methods .Keys and .Items.
| | | (The array is zero-based even
| | | with Option Base 1.)
------------------------+------------+------------+--------------------------------
Retrieve and access | X | X |
items | | |
------------------------+------------+------------+--------------------------------
Add items | X | X |
------------------------+------------+------------+--------------------------------
Implicitly add items | | X | Dicts can implicitly add items
| | | using .Item property.
------------------------+------------+------------+--------------------------------
Remove items | X | X |
------------------------+------------+------------+--------------------------------
Remove all items in | | | With collections, each item must
one step | | X | be removed in turn, or the
| | | collection destroyed and recreated.
------------------------+------------+------------+--------------------------------
Count items | X | X |
------------------------+------------+------------+--------------------------------
Return item using key | X | X |
as lookup value | | |
------------------------+------------+------------+--------------------------------
Return item using | | |
ordinal position | X | (Slow) |
as lookup value | | |
------------------------+------------+------------+--------------------------------
Return ordinal | | |
position using item | X | ?? |
as lookup value | | |
------------------------+------------+------------+--------------------------------
Retrieve and access | | X | Collection keys only used to
keys | | | look up data, not retrievable.
------------------------+------------+------------+--------------------------------
Keys optional | X | | Big + of collections, assuming keys
| | | are not needed. (Access via index.)
------------------------+------------+------------+--------------------------------
Case sensitivity | | X |
optional | | |
------------------------+------------+------------+--------------------------------
| | | Collection keys must be strings.
Keys can be any type | | X | Dict keys can have any type
| | | (except arrays), incl. mixed types.
------------------------+------------+------------+--------------------------------
Keys must be unique | X | X |
------------------------+------------+------------+--------------------------------
| | | * For collections, add code:
| | | Public Function _
| | | Contains(col As Collection, _
Supports .Exists method | Remark* | X | key As Variant) As Boolean
| | | On Error Resume Next
| | | col(key)
| | | Contains = (Err.Number = 0)
------------------------+------------+------------+--------------------------------
Preserve key order when | | X | This is because collection keys
sorting by item value | | | are write-only, not read. Poor design!
原始图像具有更多信息,排列更清晰:
Option Explicit
Sub CollectionsVSdictionaries() ' Requires ref to "Microsoft Scripting Runtime" Library
Dim c As Collection ' TypeName 1-based indexed
Dim d As Dictionary ' 0-based arrays
Set c = New Collection ' or: "Dim c As New Collection"
Set d = New Dictionary ' or: "Dim d As New Dictionary"
c.Add Key:="A", Item:="AA": c.Add Key:="B", Item:="BB": c.Add Key:="C", Item:="CC"
d.Add Key:="A", Item:="AA": d.Add Key:="B", Item:="BB": d.Add Key:="C", Item:="CC"
Debug.Print TypeName(c) ' -> "Collection"
Debug.Print TypeName(d) ' -> "Dictionary"
Debug.Print c(3) ' -> "CC"
Debug.Print c("C") ' -> "CC"
'Debug.Print c("CC") ' --- Invalid ---
Debug.Print d("C") ' -> "CC"
Debug.Print d("CC") ' Adds Key:="CC", Item:=""
Debug.Print d.Items(2) ' -> "CC"
Debug.Print d.Keys(2) ' -> "C"
Debug.Print d.Keys()(0) ' -> "A" - Not well known ***************************
Debug.Print d.Items()(0) ' -> "AA" - Not well known ***************************
'Collection methods:
' .Add ' c.Add Item, [Key], [Before], [After] (Key is optional)
' .Count
' .Item(Index) ' Default property; "c.Item(Index)" same as "c(Index)"
' .Remove(Index)
'Dictionary methods:
' .Add ' d.Add Key, Item (Key is required, and must be unique)
' .CompareMode ' 1. BinaryCompare - case-sensitive ("A" < "a")
' .CompareMode ' 2. DatabaseCompare - MS Access only
' .CompareMode ' 3. TextCompare - case-insensitive ("A" = "a")
' .Count
' .Exists(Key) ' Boolean **********************************************
' .Item(Key)
' .Items ' Returns full array: .Items(0)(0)
' .Key(Key)
' .Keys ' Returns full array: .Keys(0)(0)
' .Remove(Key)
' .RemoveAll ' ******************************************************
End Sub
选项显式
子集合VSDictionaries()'需要引用“Microsoft脚本运行时”库
Dim c作为集合的“TypeName 1”基于索引
Dim d作为基于字典的0数组
设置c=新集合”或“将c作为新集合进行调整”
设置d=新字典”或“将d标注为新字典”
c、 添加键:=“A”,项目:=“AA”:c。添加键:=“B”,项目:=“BB”:c。添加键:=“c”,项目:=“CC”
d、 添加键:=“A”,项目:=“AA”:d。添加键:=“B”,项目:=“BB”:d。添加键:=“C”,项目:=“CC”
调试。打印TypeName(c)“->”集合
调试。打印TypeName(d)“->”字典
调试。打印c(3)“->”抄送
调试。打印c(“c”)”->“CC”
“Debug.Print c(“CC”)---无效---
调试。打印d(“C”)”->“CC”
Debug.Print d(“CC”)添加键=“CC”,项=“”
调试。打印d.Items(2)“->”抄送
调试。打印d.Keys(2)“->”C“
Debug.Print d.Keys()(0)“->”A”-不太清楚***************************
Debug.Print d.Items()(0)->“AA”-不太清楚***************************
"收集方法:
“.Add”c.添加项,[键],[之前],[之后](键是可选的)
”“伯爵
“.Item(Index)”默认属性;“c.项目(索引)”与“c(索引)”相同
“.删除(索引)
“字典方法:
'.Add'd.添加键,项(键是必需的,并且必须是唯一的)
“.CompareMode”1。BinaryCompare-区分大小写(“A”<“A”)
“.CompareMode”2。数据库比较-仅限MS访问
“.CompareMode”3。TextCompare-不区分大小写(“A”=“A”)
”“伯爵
“.Exists(Key)”布尔值**********************************************
“.项目(关键)
“.Items”返回完整数组:.Items(0)(0)
“.Key(Key)
“.Keys”返回完整数组:.Keys(0)(0)
“.删除(键)
“RemoveAll”******************************************************
端接头
关于集合与词典的性能,我发现向词典中写入内容的性能与向集合中写入内容的性能类似,从词典中读取内容的时间大约是从集合中读取内容的两倍。首先,创建字典要比创建集合慢得多
以下是我在阅读、编写和创建字典/集合的100000次迭代中得到的结果:
Creating Multiple Dictionaries: 731ms
Writing To Dictionary: 494ms
Reading From Dictionary: 65ms
Creating Multiple Collections: 29ms
Writing To Collection: 459ms
Reading From Collection: 26ms
注意:添加对Microsoft脚本Runtine的引用可提高创建多个词典的速度(此处为495ms)
这是我用来测试的代码:
Option Explicit
Private p_lngTestCount As Long
Sub SetUp()
p_lngTestCount = 100000
End Sub
Sub TestAll()
CreatingMultipleDictionaries
WritingToDictionary
ReadingFromDictionary
CreatingMultipleCollections
WritingToCollection
ReadingFromCollection
End Sub
Sub CreatingMultipleDictionaries()
Const sSOURCE As String = "CreatingMultipleDictionaries"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim dcTest As Dictionary
SetUp
Dim dblTimeElapsed As Double
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
'Set dcTest = CreateObject("Scripting.Dictionary")
Set dcTest = New Dictionary
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub CreatingMultipleCollections()
Const sSOURCE As String = "CreatingMultipleCollections"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim colTest As Collection
SetUp
Dim dblTimeElapsed As Double
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
Set colTest = New Collection
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub WritingToDictionary()
Const sSOURCE As String = "WritingToDictionary"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim dcTest
SetUp
Set dcTest = CreateObject("Scripting.Dictionary")
'Set dcTest = New Dictionary
Dim dblTimeElapsed As Double
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
' Performance about the same for both ways:
dcTest.Item(CStr(i)) = "test"
'dcTest.Add CStr(i), "test"
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub WritingToCollection()
Const sSOURCE As String = "WritingToCollection"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim colTest As Collection
SetUp
Dim dblTimeElapsed As Double
Set colTest = New Collection
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
colTest.Add "test", CStr(i)
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub ReadingFromDictionary()
Const sSOURCE As String = "ReadingFromDictionary"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim dcTest
SetUp
Set dcTest = CreateObject("Scripting.Dictionary")
'Set dcTest = New Dictionary
dcTest.Add "key", "test"
Dim stTest As String
Dim dblTimeElapsed As Double
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
stTest = dcTest.Item("key")
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub ReadingFromCollection()
Const sSOURCE As String = "ReadingFromCollection"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim colTest As Collection
SetUp
Dim stTest As String
Dim dblTimeElapsed As Double
Set colTest = New Collection
colTest.Add "test", "key"
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
stTest = colTest.Item("key")
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
性能监视器类(CDevPerformanceMonitor):
选项显式
'用于日志记录的性能监视
“见:https://stackoverflow.com/questions/198409/how-do-you-test-running-time-of-vba-code
私有类型大整数
低部分一样长
长的部分
端型
#如果是VBA7,则
私有声明PtrSafe函数QueryPerformanceCounter库“kernel32”(lpPerformanceCount作为大整数)的长度为
#否则
私有声明函数QueryPerformanceCounter Lib“kernel32”(lpPerformanceCount作为大整数)的长度为
#如果结束
#如果是VBA7,则
私有声明PtrSafe函数QueryPerforma
Option Explicit
Private p_lngTestCount As Long
Sub SetUp()
p_lngTestCount = 100000
End Sub
Sub TestAll()
CreatingMultipleDictionaries
WritingToDictionary
ReadingFromDictionary
CreatingMultipleCollections
WritingToCollection
ReadingFromCollection
End Sub
Sub CreatingMultipleDictionaries()
Const sSOURCE As String = "CreatingMultipleDictionaries"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim dcTest As Dictionary
SetUp
Dim dblTimeElapsed As Double
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
'Set dcTest = CreateObject("Scripting.Dictionary")
Set dcTest = New Dictionary
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub CreatingMultipleCollections()
Const sSOURCE As String = "CreatingMultipleCollections"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim colTest As Collection
SetUp
Dim dblTimeElapsed As Double
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
Set colTest = New Collection
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub WritingToDictionary()
Const sSOURCE As String = "WritingToDictionary"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim dcTest
SetUp
Set dcTest = CreateObject("Scripting.Dictionary")
'Set dcTest = New Dictionary
Dim dblTimeElapsed As Double
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
' Performance about the same for both ways:
dcTest.Item(CStr(i)) = "test"
'dcTest.Add CStr(i), "test"
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub WritingToCollection()
Const sSOURCE As String = "WritingToCollection"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim colTest As Collection
SetUp
Dim dblTimeElapsed As Double
Set colTest = New Collection
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
colTest.Add "test", CStr(i)
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub ReadingFromDictionary()
Const sSOURCE As String = "ReadingFromDictionary"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim dcTest
SetUp
Set dcTest = CreateObject("Scripting.Dictionary")
'Set dcTest = New Dictionary
dcTest.Add "key", "test"
Dim stTest As String
Dim dblTimeElapsed As Double
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
stTest = dcTest.Item("key")
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Sub ReadingFromCollection()
Const sSOURCE As String = "ReadingFromCollection"
Dim oPerfMon As CDevPerformanceMonitor
Set oPerfMon = New CDevPerformanceMonitor
Dim i As Long
Dim colTest As Collection
SetUp
Dim stTest As String
Dim dblTimeElapsed As Double
Set colTest = New Collection
colTest.Add "test", "key"
oPerfMon.StartCounter
For i = 0 To p_lngTestCount
stTest = colTest.Item("key")
Next i
dblTimeElapsed = oPerfMon.TimeElapsed
Debug.Print sSOURCE & ": " & p_lngTestCount & " iterations. " & vbCrLf & _
"Time elapsed: " & Round(dblTimeElapsed, 0) & "ms" & vbCrLf
End Sub
Option Explicit
' Performance monitoring used in logging
' See: https://stackoverflow.com/questions/198409/how-do-you-test-running-time-of-vba-code
Private Type LARGE_INTEGER
lowpart As Long
highpart As Long
End Type
#If VBA7 Then
Private Declare PtrSafe Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
#Else
Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
#End If
#If VBA7 Then
Private Declare PtrSafe Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long
#Else
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long
#End If
Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double
Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#
Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
Low = LI.lowpart
If Low < 0 Then
Low = Low + TWO_32
End If
LI2Double = LI.highpart * TWO_32 + Low
End Function
Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
QueryPerformanceFrequency PerfFrequency
m_crFrequency = LI2Double(PerfFrequency)
End Sub
Public Sub StartCounter()
QueryPerformanceCounter m_CounterStart
End Sub
Public Function PerformanceCount() As Double
Dim liPerformanceCount As LARGE_INTEGER
QueryPerformanceCounter liPerformanceCount
PerformanceCount = LI2Double(liPerformanceCount)
End Function
Public Function MicroTime() As Double
MicroTime = Me.PerformanceCount * 1000000# / m_crFrequency
End Function
Public Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
QueryPerformanceCounter m_CounterEnd
crStart = LI2Double(m_CounterStart)
crStop = LI2Double(m_CounterEnd)
TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property