Vb.Net 2D 字典 - 非常慢

标签 vb.net

我需要创建一个 2D 字典/键值对。 我尝试过类似的事情。

enter image description here

Dim TwoDimData As New Dictionary(Of String, Dictionary(Of String, String))

'Create an empty table
For Each aid In AIDList   '(contains 15000 elements)
    TwoDimData.Add(aid, New Dictionary(Of String, String))
    For Each bid In BIDList   'contains 30 elements
        TwoDimData.Item(aid).Add(bid, "")
    Next
Next

'Later populate values.
[some code here to populate the table]

'Now access the value
'The idea is to access the info as given below (access by row name & col name)
 Msgbox TwoDimData.Item("A004").Item("B005")   ' should give the value of 2
 Msgbox TwoDimData.Item("A008").Item("B002")   ' should return empty string. No error

问题:

问题在于创建空表。创建包含空值的 TwoDimData 表需要 70 秒。其他一切似乎都很好。有什么方法可以提高性能 - 可以代替使用字典吗?

最佳答案

我建议您尝试使用Dictionary(Of Tuple(Of String, String), String)。也就是说,键是字符串对 (Tuple(Of String, String)),值是字符串。这似乎与您问题中的图表非常吻合。

Dim matrix As New Dictionary(Of Tuple(Of String, String), String)

' Add a value to the matrix:
matrix.Add(Tuple.Create("A003", "B004"), "3")

' Retrieve a value from the matrix:
Dim valueAtA003B004 = matrix(Tuple.Create("A003", "B004"))

当然你可以定义自己的 key 类型(代表两个字符串的组合) if Tuple(Of String, String)对于您的口味来说似乎太普通了。

或者,您也可以只使用(可能 jagged )二维数组,但如果您的数据是 sparse ,这可能会浪费大量空间。 (即,如果该二维矩阵中有许多空单元格);并且您将被迫使用数字索引而不是字符串。

P.S.:实际上,可以考虑将字典值类型从String更改为Integer;您的示例矩阵表明它仅包含整数,因此将它们存储为字符串可能没有意义。

P.P.S.:不要将“空”单元格的值添加到字典中。那会非常浪费。相反,您不是简单地从字典中检索值,而是检查字典是否包含该键:

Dim valueA As String = ""  ' the default value
If matrix.TryGetValue(Tuple.Create("A007", "B002"), valueA) Then
    ' the given key was present, and the associated value has been retrieved
    …
End If

关于Vb.Net 2D 字典 - 非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30225744/

相关文章:

javascript - 从 Google ReCaptcha 抓取中获取错误的验证码图像

vb.net - 如何动态调用函数

vb.net - 如何使用vb.net获取电池(笔记本电脑)信息?

.net - 使用与声明上下文变量相比有优势吗?

.net - 如何基于多态性干净地处理不同的行为

javascript - 使用 awesomium 将值提交到 html 文本框 - vb.net

.net - 如何通过运行PowerShell脚本显示实时输出?

.net - Crystal Reports 2008 和 .mdf 文件有哪些先决条件

VB.NET 设计器错误 : How to (correctly) inherit form that inherits form?

c# - 在VB.NET中初始化ExtendWebBrowser,从C#到VB.Net解析问题