[SalesForce] Find specific record in sObject list in efficient way

I have a list of type of custom sobject List<CustObject__c>
I have ID of a specific record of that object.
What is most efficient way to lookup this record in the list?
I need to optimize some code to reduce CPU time taken to execute apex code.

Best Answer

The map class has a convenient constructor that creates a map keyed by the id. That then makes lookup simple and quick:

List<Contact> l = new List<Contact>();
...
Map<Id, Contact> m = new Map<Id, Contact>(l);
...
for (...) {
    Id id = ...;
    Contact c = m.get(id);
    ...
}

However, if it is only one ID you want to find just looping over the list would be quicker (as building the map takes time and so only makes sense where multiple values are being lookup up say inside a loop).

Related Topic