Which way efficiently fill a map

bestpracticemap

In a certain scenario I need to fill a Map<Id, List<…>>
In our example let's say All the contacts linked to their accountId (Map<Id,List> contactsPerAccountId)

I'm asking myself what is more efficient way to fill this list

First option:

List<Contact> contactList = [SELECT Id, AccountId FROM Contact];
Map<Id,List<Contact>> contactsPerAccountId= new Map<Id,List<Contact>>();
for (Contact c : contactList) {
    if (contactsPerAccountId.containsKey(c.AccountId)) {
        contactsPerAccountId.get(c.AccountId).add(c);
    }
    else {
        contactsPerAccountId.put(c.AccountId, new List<Contact>{c});
    }
}

Second option:

List<Contact> contactList = [SELECT Id, AccountId FROM Contact];
Map<Id,List<Contact>> contactsPerAccountId= new Map<Id,List<Contact>>();
for (Contact c : contactList) {
    if (!contactsPerAccountId.containsKey(c.AccountId)) {
        contactsPerAccountId.put(c.AccountId, new List<Contact>());
    }
    contactsPerAccountId.get(c.AccountId).add(c);
}

There is a ton of way to fill a map, if there is another, simpler and/or faster, please free to share

Best Answer

According to stats. Only SOQL For Loops will affect the memory. If and else statements wont give you any noticeable effects.

For eg:

List<Contact> contactList = [SELECT Id, AccountId FROM Contact];
Map<Id,List<Contact>> contactsPerAccountId= new Map<Id,List<Contact>>();
for (Contact c : contactList) {
    if (contactsPerAccountId.containsKey(c.AccountId)) {
        contactsPerAccountId.get(c.AccountId).add(c);
    }
    else {
        contactsPerAccountId.put(c.AccountId, new List<Contact>{c});
    }
}

Gives a total heap size of 20414 bytes.

enter image description here

Where as This code:

List<Contact> contactList = [SELECT Id, AccountId FROM Contact];
Map<Id,List<Contact>> contactsPerAccountId= new Map<Id,List<Contact>>();
for (Contact c : contactList) {
    if (!contactsPerAccountId.containsKey(c.AccountId)) {
        contactsPerAccountId.put(c.AccountId, new List<Contact>());
    }
    contactsPerAccountId.get(c.AccountId).add(c);
}

Also gives heap size of 20414 bytes.

enter image description here

But when you do SOQL for loops

Map<Id,List<Contact>> contactsPerAccountId= new Map<Id,List<Contact>>();
for (Contact c : [SELECT Id, AccountId FROM Contact]) {
    if (!contactsPerAccountId.containsKey(c.AccountId)) {
        contactsPerAccountId.put(c.AccountId, new List<Contact>());
    }
    contactsPerAccountId.get(c.AccountId).add(c);
}

Then it gives a noticeable difference and the heap size is 4510 bytes

enter image description here

The heap size is like reduced by 75%.

Related Topic