C# 中字符串字典的最佳性能

发布于 2024-11-18 10:59:42 字数 225 浏览 3 评论 0原文

我正在设计一个包含字符串层次结构的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森末i 2024-11-25 10:59:42

Dictionary 检索值的速度非常快(接近 O(1),即无论集合大小如何,查找时间几乎恒定),因为底层实现使用哈希表。当然,如果 key 类型使用糟糕的哈希算法,那么性能可能会下降,但您可以放心,框架的 string 类型可能不会出现这种情况。

然而,正如我在评论中所问的,您需要回答几个问题:

  1. 定义最重要的性能指标,即时间(CPU)或空间(内存)。
  2. 您有什么要求?这将如何使用?你最坏的情况是什么?这是否会保存大量相对不频繁的查找的数据,是否需要在短时间内执行许多查找,或者两者都成立?

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 the key 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's string type.

However, as I asked in my comment, you need to answer a few questions:

  1. Define what performance metric is most important, i.e., Time (CPU) or space (memory).
  2. What are your requirements? How will this be used? What's your worst case scenario? Is this going to hold a ton of data with relatively infrequent lookups, do many lookups need to be performed in a short amount of time, or do both hold true?

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.

朦胧时间 2024-11-25 10:59:42

使用字典会比使用直接引用慢,因为字典必须计算哈希等。如果您确实只需要父项而不需要子项的操作(我对此表示怀疑),那么您可以将字符串一起存储在数组中与父字符串的索引。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文