为什么使用哈希图?
有人告诉我哈希图相当慢。所以我只是想知道是否使用 hashmap 还是 switch case 逻辑。
我的要求是这样的。我有一组国家名称和国家代码。我的 ListView 显示国家/地区的名称。当单击国家/地区名称项时,我必须吐司国家/地区代码。
在这种情况下,我应该维护一个 CountryNames 和 Codes 的 HashMap 并访问它以获取相应的 Code?:
myMap.put("US", 355);
myMap.put("UK", 459);
//etc
或者最好编写一个像这样的 switch case
switch (vCountryNamePos):
{
case 0: //US
vCountryCode = 355;
break;
case 1: //UK
vCountryCode = 459;
break;
//etc
}
哪个更快?如果不是Hashmap,那么在什么实际场景中会使用Map?
-琪琪
Someone told me hashmaps are rather slow. So I am just wondering whether to use hashmap or a switch case logic.
My requirement is this. I have a set of CountryNames and CountryCodes. My ListView displays the names of the countries. When an country name item is clicked, I must Toast the CountryCode.
In such a scenario, should I maintain a HashMap of CountryNames and Codes and access this to get the corresponding Code?:
myMap.put("US", 355);
myMap.put("UK", 459);
//etc
Or is it better to write a switch case like so
switch (vCountryNamePos):
{
case 0: //US
vCountryCode = 355;
break;
case 1: //UK
vCountryCode = 459;
break;
//etc
}
Which is faster? If not Hashmaps, then in what practical scenarios would a Map be used?
-Kiki
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于两个值,切换会更快。哈希映射将始终至少检查密钥是否相等,因此它无法击败一两个 .equals() 测试。
对于许多值,哈希会更快。交换机必须测试每个值,直到找到正确的值。
对于少量值(例如最多 10 个左右),最好使用开关。它会变得更轻、更快。
对于大量值(超过 50 个),首选哈希。哈希不必检查所有值,因此当值的数量增加时,它会比 switch 更快。
对于 10~50 个值,我建议您采用您认为更具可读性的值,因为性能会相似。
现在,如果您正在研究编译时已知的静态字符串的极端性能,您可以考虑像 gnuperf 这样的代码生成工具。
如果你在编译时不知道你的字符串,但你知道它们会相当短并且长度相当均匀,或者具有公共前缀,那么使用 Trie 数据结构可能会是最快的。
如果您想在大量异构字符串或可能不是字符串的对象上保持性能,那么 HashMap 是最佳选择。当对象数量非常多(数十亿或更多)时,它几乎是无与伦比的。
For two values, a switch will be faster. A hashmap will always at least check for equality of your key, so it can't beat one or two .equals() tests.
For many values, a hash will be faster. A switch has to test every value until it finds the right one.
For a small number of values (say up to 10 or so), prefer a switch. It's gonna be lighter and faster.
For a big number of values (in upwards of 50), prefer a hash. A hash will not have to check all values, so it will be faster than a switch when the number of values increases.
For 10~50 values, I'd suggest you do what you feel is more readable because the performance is gonna be similar.
Now if you are looking into extreme performance on static strings known at compile time, you may look into code-generating tools like gnuperf.
If you don't know your strings at compile time but you know they are gonna be decently short and decently uniform in length, or with common prefixes, you are probably gonna be fastest with a Trie data structure.
If you want to keep performance on great number of very heterogeneous strings, or on objects that may not be Strings, then HashMap is the way to go. It's pretty much unbeatable when the number of objects is very high (in the billions or more).