[SalesForce] List vs Map iterations

In this list to list code where you find Id's on a query and insert the Id's into another pre-existing list worse, better, or same as the map to map code below it? I am trying to use maps to be easier on limits, however, I don't see an advantage when having to still iterate over both maps. They both take the same amount of iterations to finish, in about the exact same lines of code.
List to List version:

List<Account> uniqueIdMatchAcc = new List<Account>();
if(allUniqueIDs.size()>0){
  uniqueIdMatchAcc = [Select id, unique__c From Account Where unique__c in :allUniqueIDs];
}  
if(uniqueIdMatchAcc.size() > 0 ){ //if unique matches were found, feed Id's into registrationList created earlier
   for(Account uma : uniqueIdMatchAcc){
        for(registration crl : registrationList){
            if(uma.unique__c == crl.acc.unique__c){
                crl.acc.Id = uma.Id;
            }
        }
    }
}

Map to Map version, better to use, worse, or same?

        Map<String, account> uniqueIdMatchAccMap = new Map<String, account>();         
        for(Account a: [Select unique__c From Account Where unique__c in :allUnique]){
            uniqueIdMatchAccMap.put(a.unique__c, a);
        }
        if(uniqueIdMatchAccMap.size() > 0 ){
            for(String unique : uniqueIdMatchAccMap.keySet()){
                for(Integer i : accountMap.keySet()){
                    if(accountMap.get(i).unique__c == unique){
                        accountMap.id.put(i, uniqueIdMatchAccMap.get(unique));
                    }
                }
            }
        }

Could I be doing this better?

Adding to this question, part 2, how would I get it to add the account into accountMap without erasing everthing that was originally in the map. accountMap.put(i, ufidMatchAccMap.get(unique)) wipes out all that was and insterts only the Id, where as I am looking to put in only the Id and leave what was as well?

Best Answer

Your second solution is even worse in aspect of efficiency. Because Map in apex is implemented in HashMap and get is of logN complexity if I remember correctly. But this does not mean you shouldn't be using Map in this case. What you need to do is to change the second version into this:

if(uniqueIdMatchAccMap.size() > 0 ){
    for(registration rl : registrationList){
        Account a = uniqueIdMatchAccMap.get(rl.acc.unique__c);
        if(a != null)
        {
            rl.acc.Id = a.Id;
        }
    }
}

As you have already put everything into a map, there is no reason you should loop through the map's keySet in this case. And since you get rid of one level's loop and use map .get() method instead, the efficiency of this code will be significantly better.

Related Topic