C# 中字符串字典的最佳性能
我正在设计一个包含字符串层次结构的 C# 类,其中每个字符串都有 0 或 1 个父级。
我倾向于使用 Dictionary
来实现此功能,其中键是子项,值是父项。字典可能有大量的值,但我不能说出确切的大小。这看起来应该比创建引用父级的复合包装器执行得更快,但我可能是错的。
我可以采取其他方法来确保更好的性能速度吗?
I am designing a C# class that contains a string hierarchy, where each string has 0 or 1 parents.
My inclination is to implement this with a Dictionary<string,string>
where the key is the child and value is the parent. The dictionary may have a large amount of values, but I can't say the exact size. This seems like it should perform faster than creating composite wrapper with references to the parent, but I could be wrong.
Is there an alternative approach I can take that will ensure better performance speed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从
Dictionary
检索值的速度非常快(接近 O(1),即无论集合大小如何,查找时间几乎恒定),因为底层实现使用哈希表。当然,如果key
类型使用糟糕的哈希算法,那么性能可能会下降,但您可以放心,框架的string
类型可能不会出现这种情况。然而,正如我在评论中所问的,您需要回答几个问题:
Dictionary
类还在内部使用一个数组,该数组会随着您添加项目而增长。这对你来说可以吗?同样,在任何人都能给您完整的答案之前,您需要更具体地说明您的要求。Retrieving values from a
Dictionary<K,V>
is extremely fast (close to O(1), i.e., almost constant time lookup regardless of the size of the collection) because the underlying implementation uses a hash table. Of course, if thekey
type uses a terrible hashing algorithm than the performance can degrade, but you can rest assured that this is likely not the case for the framework'sstring
type.However, as I asked in my comment, you need to answer a few questions:
The
Dictionary<K,V>
class also uses an array internally which will grow as you add items. Is this okay for you? Again, you need to be more specific in terms of your requirements before anyone can give you a complete answer.使用字典会比使用直接引用慢,因为字典必须计算哈希等。如果您确实只需要父项而不需要子项的操作(我对此表示怀疑),那么您可以将字符串一起存储在数组中与父字符串的索引。
Using a Dictionary will be slower than using direct references, because the Dictionary will have to compute a hash etc. If you really only need the parent and not the child's operation (which I doubt), then you could store the Strings in an array together with the index of the parent String.