+ Start a Discussion
Norm CopelandNorm Copeland 

Aspiring SF Dev needing help 😃 System.LimitException: Apex CPU time limit exceeded

Hi all, I've just written my second trigger and it seems that I'm needing to learn more about how to optimize my code. My trigger runs through the campaign members of a campaign and changes the member status of any email duplicates (but leaves one) so  that an email isn't sent twice to one emails. As a nonprofit many of our donors share an email address in their household so we removing the email addresses from the contacts isn't possible. To help with this, I wrote the trigger below. It worked great in testing on a few hundred campaign members but when I tested it on a few thousand I recieved the dreaded 'System.LimitException: Apex CPU time limit exceeded'.

Could anyone help me optimize this code? I'd love to learn how and apply this knowledge to future triggers. Thank you!
 
trigger CleanEmailAddresses on Campaign (after update) {

	for (Campaign camp : Trigger.new) {
				
		// Check for clean email addresses trigger
		if (camp.clean_emails__c == true) {

			if (camp.IsActive && camp.Status != 'Completed' && camp.Status != 'Aborted') {

			// Counters used later
			Integer uniqueEmailCount = 0;
			Integer dupeCounter = 0;

			// Initialize list that will hold duplicate email addresses
			List<CampaignMember> theseAreTheDupes = new List<CampaignMember>();

			// Check to see if campaign has member status 'Email Duplicate'
			List<CampaignMemberStatus> campaignStatuses = [SELECT Id,
																  Label,
																  CampaignId
															 FROM CampaignMemberStatus
														    WHERE CampaignId = :camp.Id AND
														    	  Label 	 = 'Email Duplicate'];

			// No? Then create it
			if (campaignStatuses.size() == 0) {

				CampaignMemberStatus newCampaignMemberStatus = new CampaignMemberStatus();
				newCampaignMemberStatus.Label 				 = 'Email Duplicate';
				newCampaignMemberStatus.CampaignId 			 = camp.Id;
				insert newCampaignMemberStatus;

			}

			// Create list of email addresses already in campaign that do not have duplicate status
			List<CampaignMember> campaignMembers = [SELECT Id,
														   Email,
														   Status
													  FROM CampaignMember
													 WHERE CampaignId 	= :camp.Id AND
													 	   Status      != 'Email Duplicate' AND
													 	   HasResponded = false];

			
			// Initialize string set that will hold list of unique email addresses
			Set<string> uniqueEmails = new Set<string>();


			// Populate set with unique emails
			for (CampaignMember addToUniqueEmailSet : CampaignMembers) {
								
				uniqueEmails.add(addToUniqueEmailSet.Email);

			}

			// Loop through each unique email address
			for (String uniqueEmailList: uniqueEmails){
				
				// Loop through email campaign member
				for (Integer i = 0; i < campaignMembers.size(); i++) {
					

					// Check to see if current campaign member's email address matches unique address of current iteration
					if (campaignMembers.get(i).Email == uniqueEmailList) {

						// Count number of dupes
						uniqueEmailCount = uniqueEmailCount + 1;

						// Check to see if duplicate is the first one or note
						if (uniqueEmailCount > 1) {

							// If dupe is not the first, add to list of campaign members to change later
							theseAreTheDupes.add(campaignMembers.get(i));
							

						}

					}

				}
				
				// Reset counter
				uniqueEmailCount = 0;

			system.debug ('dupe list size: '+ theseAreTheDupes.size());	

			}

			if (theseAreTheDupes.isEmpty() == false) {

				for (CampaignMember cmChangeStatus : theseAreTheDupes) {

					theseAreTheDupes.get(dupeCounter).Status = 'Email Duplicate';
					dupeCounter = dupeCounter + 1;

				}

				update theseAreTheDupes;

			}

			} else {

				camp.addError('Whoa there partner! 🐴  Emails can not be cleaned from inactive, aborted or completed campaigns!');

			}

		}

	}

}

 
Amit Chaudhary 8Amit Chaudhary 8
I found below issue in your trigger
1) SOQL inside the for loop
2) For loop inside for loop
3) DML inside the for loop.

Please check below post. I hope that will help you
1) http://amitsalesforce.blogspot.com/2015/06/trigger-best-practices-sample-trigger.html
2) http://amitsalesforce.blogspot.com/2016/09/collection-in-salesforce-example-using.html


Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org. 

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail


Let us know if this will help you
 
Shiva RajendranShiva Rajendran
Hi Norm ,

I have notified few code's which doesn't follow the trigger best practises.
for (Campaign camp : Trigger.new) {
				
		// Check for clean email addresses trigger
		if (camp.clean_emails__c == true) {

			if (camp.IsActive && camp.Status != 'Completed' && camp.Status != 'Aborted') {

			// Counters used later
			Integer uniqueEmailCount = 0;
			Integer dupeCounter = 0;

			// Initialize list that will hold duplicate email addresses
			List<CampaignMember> theseAreTheDupes = new List<CampaignMember>();

			// Check to see if campaign has member status 'Email Duplicate'

// Note this line
			List<CampaignMemberStatus> campaignStatuses = [SELECT Id,
																  Label,
																  CampaignId
															 FROM CampaignMemberStatus
														    WHERE CampaignId = :camp.Id AND
														    	  Label 	 = 'Email Duplicate'];
}


You are doing 2 soql query for each camp  after update , so suppose if you have updated more than 150 camps in a stretch ,then the code will break. Try updating 150 or above camps ,you will too many soql queries exception

Also soql call is time consuming. That may be the reason for your System.LimitException: Apex CPU time limit exceeded exception.

 

trigger CleanEmailAddresses on Campaign (after update) {


            Integer uniqueEmailCount = 0;

            Integer dupeCounter = 0;  

List<Id> campaignId=trigger.newMap.keySet();
List<CampaignMemberStatus> campaignStatuses = [SELECT Id, Label, CampaignId FROM CampaignMemberStatus WHERE CampaignId in :campaignId AND Label = 'Email Duplicate'   ];
List<Map,List<CampaignMemberStatus>> campaignAndStatusMap=new List<Map,List<CampaignMemberStatus>>();
for(CampaignMemberStatus oo: campaignStatuses)
{
          if(campaignAndStatusMap.contains(oo.CampaignId))
          {
              List<CampaignMemberStatus> newListCampaignStatus=campaignAndStatusMap.get(oo.CampaignId);
              newListCampaignStatus.add(oo);
             campaignAndStatusMap.put(oo.CampaignId,newListCampaignStatus);
          }
        else
        {
                List<CampaignMemberStatus> newListCampaignStatus=new List<CampaignMemberStatus> ();
                newListCampaignStatus.add(oo);
                campaignAndStatusMap.put(oo.CampaignId,newListCampaignStatus);


          }
}

Now you would have a map of campaign and its related campign member status .

Do the same for CampaignMember and get 
List<Map,List<CampaignMember>> campaignMembersMap=new List<Map,List<CampaignMember>>();
Get this map data.
List<CampaignMemberStatus> toBeInsertCampaignMemberStatus=new List<CampaignMemberStatus>();
 List<CampaignMember> theseAreTheDupes = new List<CampaignMember>();
for(Id campaignID:campaignMembersMap.keySet())
{

              if (campaignAndStatusMap.get(campaignID).size() == 0) {

                CampaignMemberStatus newCampaignMemberStatus = new CampaignMemberStatus();
                newCampaignMemberStatus.Label               = 'Email Duplicate';
                newCampaignMemberStatus.CampaignId          = campaignID.Id;
                toBeInsertCampaignMemberStatus.add(newCampaignMemberStatus);
 
            }
        List<CampaignMember> allCampaignMemberofThisCampaign=campaignMembersMap.get(campaignID);
        Set<string> uniqueEmails = new Set<string>();
       for (CampaignMember addToUniqueEmailSet : allCampaignMemberofThisCampaign) {
                              
              uniqueEmails.add(addToUniqueEmailSet.Email);
          }
 
           //Can improve this logic further
          for (String uniqueEmailList: uniqueEmails){
                         // Loop through email campaign member
                      for (Integer i = 0; i < campaignMembers.size(); i++) {
                     
 
                         // Check to see if current campaign member's email address matches unique address of current iteration
                    if (campaignMembers.get(i).Email == uniqueEmailList) {
 
                        // Count number of dupes
                        uniqueEmailCount = uniqueEmailCount + 1;
 
                        // Check to see if duplicate is the first one or note
                        if (uniqueEmailCount > 1) {
 
                            // If dupe is not the first, add to list of campaign members to change later
                            theseAreTheDupes.add(campaignMembers.get(i));
                             
 
                        }
 
                    }
                }
                 
                // Reset counter
                uniqueEmailCount = 0;
 
            system.debug ('dupe list size: '+ theseAreTheDupes.size());
 
            }
 







if (theseAreTheDupes.isEmpty() == false) {

                for (CampaignMember cmChangeStatus : theseAreTheDupes) {
 
                    theseAreTheDupes.get(dupeCounter).Status = 'Email Duplicate';
                    dupeCounter = dupeCounter + 1;
 
                }
 insert toBeInsertCampaignMemberStatus;
                update theseAreTheDupes;

            }
 
            } else {
                camp.addError('Whoa there partner! 🐴  Emails can not be cleaned from inactive, aborted or completed campaigns!');

            }
 
    

}

This is the modification i have made. Can't assure it will be bug, since i made the edit directly in this page. I have made your code bulk processing.
Let me know if you need further help.
Thanks and Regards,
Shiva RV