All,
Can anyone please let me know exactly what are the performance issues between the 2? The site : CodeRanch provides a brief overview of the internal calls that would be needed when using keySet() and get(). But it would be great if anyone can provide exact details about the flow when keySet() and get() methods are used. This would help me understand the performance issues better.
First of all, this depends entirely on which type of
Mapyou’re using. But since the JavaRanch thread talks aboutHashMap, I’ll assume that that’s the implementation you’re referring to. And let’s assume also that you’re talking about the standard API implementation from Sun/Oracle.Secondly, if you’re concerned about performance when iterating through your hash map, I suggest you have a look at
LinkedHashMap. From the docs:HashMap.entrySet()
The source-code for this implementation is available. The implementation basically just returns a new
HashMap.EntrySet. A class which looks like this:and a
HashIteratorlooks likeSo there you have it… That’s the code dictating what will happen when you iterate through an
entrySet. It walks through the entire array, which is as long as the map’s capacity.HashMap.keySet() and .get()
Here you first need to get hold of the set of keys. This takes time proportional to the capacity of the map (as opposed to size for the
LinkedHashMap). After this is done, you callget()once for each key. Sure, in the average case, with a good hashCode-implementation this takes constant time. However, it will inevitably require lots ofhashCode()andequals()calls, which will obviously take more time than just doing aentry.value()call.