I have a trigger in which I want to cater for the requirement to compare records during a bulk insert or update. I want to make sure of the following:

  • No 2 records in the bulk being inserted/updated have the same dates (in a date range)

  • that there are not records already existing in the DB which meet this criteria.

I therefore create a set of records which contains a) the records being inserted, + b) records retrieved via a SOQL query for potential matches.

I then want to loop through my list of records being inserted/updated and the set of records which I need to compare against. My for loop is as follows

    for(myObj_c itemBeingProcessed : newItems){
        for(myObj_c itemForComparison : completeSetForComparison){

            if((itemBeingProcessed.Id != null && itemBeingProcessed.Id == itemForComparison.Id)
                                          || (itemBeingProcessed == itemForComparison)){

            //main logic....

However the line itemBeingProcessed == itemForComparison causes the CPU limit to exceed if for example I insert 200 records.

Does anyone know of a way I can compare the objects in my for loop without straining the CPU limits? It seems if comparing full object references it smashes the CPU limits.

  • 1
    Do you actually care about complete equality? Surely you are looking for changes to specific fields. Removing the double loop will help but full comparison is expensive and it only makes sense that it would be. – Adrian Larson Oct 18 '16 at 17:01
  • Also are the collections you use for comparison basically just trigger.new and trigger.old? – Adrian Larson Oct 18 '16 at 18:28
  • Hi, Thanks Adrian. No, for my comparisons it's basically trigger.new + records which already exist in the DB and are not part of the trigger context. For trigger.new I need to compare that 2 records do not contain start and end dates (there are start and end date fields) which could be in the same date range. I didn't post that logic above. For my 'if statement' above I was checking,;if the ID's are the same (in otherwords it;s a before update) but for new records they don't have id's yet so I want to make sure I don't compare the record in the for loop with itself. – RedQueries Oct 18 '16 at 18:44
  • Do you know how I can ensure I'm not comparing 2 records if they don't have an ID yet (as its a before insert). Thanks. – RedQueries Oct 18 '16 at 18:46
  • Um. I think you need to perhaps edit your post to share a more complete picture. It's hard to follow in the comments. – Adrian Larson Oct 18 '16 at 18:48

Your Answer

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

Browse other questions tagged or ask your own question.