0

Iterating with Map with Keys vs Values :

As in Apex we need to write code efficiently for avoiding memory issues and CPU time limit everywhere, I need to understand how to iterate over a map efficiently. Some say by values and some by keys.

for (Object o : map.values()){
//your logic
}

or

for (Id eachOLIId : mapItems.keySet()) {
OpportunityLineItem lineITem = mapItems.get(eachOLIId);
// your logic
}
  • 1
    Depends on the scenario. In your example I would say by value. If by using values you would have to perform additional logic to filter I would say use keys. In your case there’s is no need for a map at all and you could just stick with a list. – Eric Oct 14 '17 at 14:09
0

According to me, following for loop is iterating over a list which can have duplicate values.

for (Object o : map.values()){
//your logic
}

And below you are iterating over a Set<Id>() which does not contain duplicates.

for (Id eachOLIId : mapItems.keySet()) {
OpportunityLineItem lineITem = mapItems.get(eachOLIId);
// your logic
}

Secondly, if you have multiple inner for loops then that inner for loops can be eliminated with the use of map. and that moment you will get performance benefit and hence minimize CPU limit also.

Basically, how you are putting your logic to achieve your business case depends on scenarios.

0

Unless you're noticing a performance issue, use whichever you prefer. The difference in performance is negligible in most cases. The only time you definitely want to use values is if you have a large map with a custom key that has a high collision rate (and if you have that problem, you should be optimizing your custom key).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.