I have a Web Service class. When I call the method from this class, I get "Apex CPU time limit exceeded" error. The for
loops are causing this trouble. Here's my not efficient code:
List<Task> tasks = [SELECT Id, WhoId FROM Task];
List<Contact> contacts = [SELECT Id FROM Contact];
for (Task t : tasks){
for(Contact c : contacts){
if (t.WhoId == c.Id){
//some logic here
}
}
}
This piece of code matches the related Task
and Contact
objects. How to make it more efficient? Is there a way to reduce the number of loops here to one?