I’m already iterating over several hashmaps each of sizes 20-40 items so would it make more sense to find an item just by adding an if condition while iterating or using a single get(key) operation ? Which approach would give more performance.
I know for accurate results I should rely on profiling results but since I’m not too familiar with profiling, wanted an expert opinion.
Edit:
Here is my code:
for (HColumn col : lobColumns) {// lobcolumns is a list but I also have hashmap already built containing same elements as this list
switch (ByteBufferToInt(col.getName())) {
case .......:
break;
case .......:
break;
case .......:
break;
case .......:
break;
case .......:
break;
}
if (ByteBufferToInt(col.getName()).intValue()==currentUserId()){// here is what I'm using as replacement for hashmap `get()`
.....
}
}
lobcolumns is a list but I also have hashmap already built containing same elements as this list. This list/map contains a few constant & a few variable objects, for constants I use switch case for efficient lookups & for finding a single special variable item I need to need to decide whether to use hashmap get() or using if while already iterating.
Well I mean let’s look at it. The
getoperation isO(1)or constant time with a perfect hash function in the worst case. Whereas iteration isO(n)in the worst case. If you have thekeyahead of time just invokegetthere is no need to iterate over everything.Update
The following line:
Your comment was that you have all of these values stored in a
HashMapalready. If the map is defined as so:The
ifstatement moves outside of the for loop and becomes the following:This reduces the if to only be executed once, as it is now outside of the
forloop.