Dictionary(StringComparer) 与 Dictionary并存储 key.ToUpper :您应该选择哪一个?
免责声明:也许是微 YAGNI 优化,但听我说。
问题是实现一个不区分大小写的查找表。
- 我的老方法:在填充字典时,在插入之前将键大写。当有人给你一个查找键时,将键大写。
- 新方法(我今天了解到):Dictionary 接受 IComparer 实现,因此我可以传入 StringComparer.InvariantCultureIgnoreCase 。我认为它将委托给 String.Compare(x, y, SomeIgnoreCaseEnum)
新方法的优点是我不需要确保在完成查找的 n 个位置中的每个位置执行 .ToUpper()反对字典。
我的问题是哪一个更有效率?我想只是好奇......
更新:注意我不需要知道插入的原始密钥。此外,所使用的密钥与文化无关。
Disclaimer: Maybe be micro-YAGNI-optimizing but hear me out ..
The problem is to implement a case-insensitive lookup table.
- My old-skool way: While populating the dictionary, upper-case the key before inserting. Upper-case the key when someone gives you a key to lookup.
- The new way (I learned about it today): Dictionary takes in an IComparer implementation, so I could pass in
StringComparer.InvariantCultureIgnoreCase
. I think it would delegate to String.Compare(x, y, SomeIgnoreCaseEnum)
The new way has an advantage in that I don't need to ensure that a .ToUpper() is performed at each of the n places where a lookup is done against the dictionary .
My question is which one is more efficient ? Just curious I guess...
Update: Note I don't need to know the original key that was inserted. Also the keys that are used are culture agnostic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
大写可能会更有效,因为它可以进行序数比较......但我非常怀疑这对您来说是性能瓶颈。与以往一样,在根据性能进行代码更改之前进行分析。
最终,指定字符串比较:
It's possible that upper-casing would be more efficient, as it could then do an ordinal comparison... but I very much doubt that this is a performance bottleneck for you. As ever, profile before you commit to a code change on the basis of performance.
Ultimately, specifying the string comparison:
检查此条目。今天仍然有效。
摘录:来自 MSDN 的“在 Microsoft .NET 2.0 中使用字符串的新建议”
Check this entry. It's still valid today.
Excerpt: From MSDN's "New Recommendations for Using Strings in Microsoft .NET 2.0"
我不知道性能如何,但我更喜欢 StringComparer 选项。使用 ToUpper,您会丢失信息(原始大小写)。确实,你可能不需要它,但有一天你可能不需要它,并且感觉不需要再做任何工作来保存它(因此不受 YAGNI 原则的影响)。
有一天,我也会忘记给 ToUpper 打电话,陷入痛苦的世界。但我的单元测试当然会拯救我。
I don't know about the performance but I prefer the StringComparer option. With ToUpper you lose information (the original casing). True you might not need it, but one day you might and it doesn't feel like any more work to keep it (thus safe from the YAGNI principle).
I would also one day forget to call ToUpper and be in a world of hurt. But my unit tests would save me of course.
我会接受 Oded 的“Go profile!”评论:)这是一个显而易见的建议。
根据我的测试(源代码此处)
1M包含键查找,
:971 毫秒
我发现带有注入比较器选项的字典可以执行更好且更少的麻烦。所以我不再需要 ToUpper() 了。
I'd have accepted Oded's 'Go profile!' comment :) which was a Master-of-the-obvious suggestion.
From my test (source code here)
For 1M ContainsKey lookups,
: 971 msecs
I find Dictionary with an injected Comparer option to perform better and less hassle. So no more ToUpper() for me.