posted 15 years ago
[Tim]: The keyset is a core part of the HashMap data structure. The entryset has to be constructed by enumerating through the HashMap element by element, which is an extra layer of code. So yes, it's true that a keyset is slightly more efficient in most cases.
I don't agree. An EntrySet is just a thin wrapper providing a view of objects that already exist inside the HashMap. Specifically, there is an array of HashMap.Entry obects, which implement Map.Entry. The EntrySet just provides access. There's no need to iterate through the whole map just to construct an EntrySet.
The reason FindBugs points out a possible performance issue is that, if you need to access every key and value, there is absolutely no reason to call get() on each key. Each key and value are already stored right next to each other anyway, internally, in a HashMap.Entry instance. So when you iterate an EntrySet, you're just accessing these elements directly. If instead you call get(), you're invoking hashCode() and causing the HashMap to do a lookup in its internal array. Admittedly this is an O(1) operation, but it's always going to take a bit longer than simply using Entry.getValue(), and there's no reason to make such a call when the key and value are stored next to each other in the first place.
I agree with the points about measuring performance, though, and in many, many applications, the difference will be insignificant. It's not likely to be worth your time to change your existing code for this. But I think it's perfectly sensible to get in the habit of iterating using entrySet() in the first place, for all new code.
[ October 31, 2008: Message edited by: Mike Simmons ]