Wanted to understand what is more efficient to do bulk insert/updates on records.
Opportunity opportunity = new Opportunity();
for(Id accountId : accountIds) {
opportunity.put('Name', 'Opportunity ' + accountId);
opportunity.put('AccountId', accountId);
opportunity.put('StageName', 'Prospecting');
opportunity.put('Amount', 0.0);
opportunity.put('CloseDate', Date.Today().addDays(90));
}
insert opportunity;
OR
List<Opportunity> opportunities = new List<Opportunity>();
for(Id accountId : accountIds) {
Opportunity opp = new Opportunity();
opp.Name = 'Opportunity ' + accountId;
opp.AccountId = accountId;
opp.StageName = 'Prospecting';
opp.Amount = 0.0;
opp.CloseDate = Date.Today().addDays(90);
opportunities.add(opp);
}
insert opportunities;
Best Answer
Neither of these examples uses a
Map
. You can't perform DML on aMap
, although if you have, say, aMap<Id, sObject>
you can doinsert myMap.values();
Your first example is entirely wrong. It will insert exactly one Opportunity with the
AccountId
set to the lastId
inaccountIds
, which is not what you want.The second example is correctly bulkified.