字典访问:复合键与连接字符串索引
我有一个字典,我想使用一个由字符串 (AcctNum
) 和日期 (BalDate
) 组合而成的键来访问它。
在我看来,最简单的方法是通过简单地将日期转换为字符串并连接来创建密钥:
MyKey = BalDate.ToString & "|" & AcctNum
我知道我还可以选择通过编写单独的类并覆盖 GetHashCode() 和
Equals()
是此解决方案。
对我来说,连接字符串是一个更简单的解决方案,尽管有些不太优雅。我是否缺少一些令人信服的理由来说明为什么我应该采用复合键类方法?
此查找是我正在从事的项目的关键,因此性能是我的主要目标(可读性紧随其后)。
I have a dictionary that I want to access with a key that is the combination of a string (AcctNum
) and a date (BalDate
).
It seems to me the simplest approach is to create the key by simply converting the date to a string and concatenating:
MyKey = BalDate.ToString & "|" & AcctNum
I know I also have the option of creating a composite key by writing a separate class and overriding GetHashCode()
and Equals()
a la this solution.
To me, the concatenated string is a simpler, if somewhat less elegant, solution. Am I missing some compelling reason why I should go with the composite key class approach?
This lookup is the crux of the project I am working on, so performance is my main objective (with readability a close second).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果性能对您来说最重要,那么使用单独的对象可能是更好的解决方案:每次准备查找键时,您都可以节省将日期格式化为字符串的时间。此外,如果您决定向键添加更多部分,则拥有多部分键更容易扩展:忽略连接中缺失的元素比忽略构造函数中缺失的参数要容易得多。
If performance is most important to you, then using a separate object is likely to be a better solution: you will save on formatting a date as a string every time you are preparing a lookup key. In addition, having a multipart key is easier to extend, should you decide to add more parts to the key: it is much easier to overlook a missing element of a concatenation than a missing parameter of a constructor.
使用元组作为字典的键。
元组比连接字符串更简单且不易出错。
它比使用单独的类更好,因为您不需要自己重写 GetHashCode() 和 Equals()。
Use a Tuple as key for your dictionary.
Tuples are simpler and less error-prone than concatenating strings.
It is better than using a separate class, since you don't need to override GetHashCode() and Equals() yourself.
您还可以通过继承
Dictionary(Of TKey, TValue)
来创建专门的集合。我认为复合键和连接字符串之间的速度差异并不大。使用复合键,您不必将日期转换为字符串;但是,您必须计算不同的哈希码并将它们组合起来。但是,通过使用字典的专门实现,您可以隐藏这些实现细节,并随时决定更改生成键的方式,而不会影响程序的其他部分。
You could also create a specialized collection by inheriting from
Dictionary(Of TKey, TValue)
I do not think that the difference in speed between a composite key and a concatenated string is substantial. With a composite key, you do not have to convert the date to a string; however, you will have to calculate different hash codes and to combine them. By using a specialized implementation of a dictionary, however, you can hide these implementation details and at any time decide to change the way you generate the keys without affecting other parts of your program.