1

We are using the Database.Insert(leads, false); We want only the the ids that where insert. We have a lot of leads to be checked if we use

for (Database.SaveResult result: results) {
     if (result.isSuccess()) {
        leadsInserted.add(result.getId());                            
     }   
}

This can take time depending on how many leads are being introduced. Do we have a better way ?

1 Answer 1

4

There is no way to do this without an iteration, as the only viable alternative, using a Map, won't work with one or more null values present in the list.

You don't need to check success first:

Set<Id> insertedLeads = new Set<Id>();
for (Database.SaveResult result: results) {
  insertedLeads.add(result.getId());                            
}
insertedLeads.remove(null);

This should take approximately half the time. Note that we can't use any other faster method, as there is no faster method available to us.

Further, if you're just interested in the Id values, use the original insert list:

Set<Id> insertedLeads = new Set<Id>();
for (lead record: source) {
  insertedLeads.add(source.id);                            
}
insertedLeads.remove(null);

This eliminates the method calls and provides even better performance.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .