3

How can i handle this error in salesforce ? i know that it occurs due to inner loops

my code is

for(tblproperty__c t:CheckAvailability)
{
   for(tblpropertyamenities__c te: CheckPropertyAmenity)
  {
    if(t.fPropertyID__c==te.fPropertyIDDB__c)
     {
      CheckAvailability1.add(t);
      }
 }
}
  • The Maximum CPU time on the salesforce servers is used to stop long running processes. The error will be thrown at some point after your code has been running for 10,000 milliseconds (60,000 for Asynchronous code). The line the error happens on does not mean that line is the problem. Your code looks fine and shouldn't of caused this error. There is most likely code that executed before that code that caused the problem. – BarCotter Oct 23 '14 at 8:13
  • How many records are in CheckPropertyAmenity and CheckAvailability? – BarCotter Oct 23 '14 at 8:16
  • 1173 records in both – Riaz Muhammad Oct 23 '14 at 10:45
  • Your loop will iterate 1,375,929 times (1,173 x 1,173). Are you limiting your SOQL with a where clause so that you are only selecting certain records or are you selecting all records? Providing a bit more of your code may help other people understand what you are trying to achieve. – BarCotter Oct 23 '14 at 11:02
2

If both lists are large then performance will degrade exponentially. You can change the performance to be linear with the number of list items like this:

Set<Id> propertyIds= new Set<Id>();
for(tblpropertyamenities__c te : CheckPropertyAmenity) {
    propertyIds.add(te.fPropertyIDDB__c);
}
for(tblproperty__c t : CheckAvailability) {
    if (propertyIds.contains(t.fPropertyID__c)) {
        CheckAvailability1.add(t);
    }
}

(If you needed access to the tblpropertyamenities__c fields, instead of creating a Set<Id> you could create a Map<Id, tblpropertyamenities__c>.)

Though it would be a little surprising to hit the CPU limit unless the lists are very large.

  • i got it, i have done it through adding break statement in my if condition when true – Riaz Muhammad Oct 23 '14 at 8:21
  • @RiazMuhammad That will reduce the amount of time by a factor of 2 on average so when the list gets 2 times bigger than it is now the problem will return... – Keith C Oct 23 '14 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.