views:

89

answers:

1

Hi,

Someone told me hashmaps are rather slow. So I am just wondering whether to use a hashmap or simply 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

+3  A: 

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).

Jean
Note that in this particular case, you might want to use something like Android's SparseArray to avoid autoboxing/unboxing.
Romain Guy