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
andelse
statements wont give you any noticeable effects.For eg:
Gives a total heap size of 20414 bytes.
Where as This code:
Also gives heap size of 20414 bytes.
But when you do
SOQL for loops
Then it gives a noticeable difference and the heap size is 4510 bytes
The heap size is like reduced by 75%.