top of page
Blog Page(1902x420).jpg

Keep your business ahead with

Insights That Drive Innovation

How to Efficiently Handle Loops in Salesforce Apex Code

Updated: Sep 16

Loops are essential in almost every programming language, and Salesforce Apex Code is no exception. However, careless handling of loops can quickly lead to performance bottlenecks, hitting governor limits, or even failing deployments.

How to Efficiently Handle Loops in Salesforce Apex Code

This blog explores Apex best practices for handling loops effectively so your apex coding practice stays maintainable and scalable.


Why Loop Efficiency Matters in Salesforce Apex Code

In Salesforce, governor limits are in place to ensure no single piece of code monopolizes shared resources. Poor loop design can:


  • Cause SOQL 101 errors (too many queries)

  • Hit DML operation limits

  • Slow down your applications

  • Degrade user experience

So, adopting good Apex loop practices is a nice-to-have, and it's essential for every developer working in the Salesforce ecosystem.

Apex Best Practices for Efficient Loops

Let’s look at actionable ways to improve your loop handling in Salesforce Apex Code.


  1. Avoid SOQL & DML Statements Inside Loops

One of the most common mistakes is placing SOQL queries or DML operations inside loops. Each iteration can add to the governor limit count, leading to exceptions.


Bad Example: apex CopyEdit



for(Account acc : accountList) {

    Contact[] relatedContacts = [SELECT Id FROM Contact WHERE AccountId =:acc.Id];

    update relatedContacts;

}

Good Example:

apex

CopyEdit



Set<Id> accountIds = new Set<Id>();
for(Account acc : accountList) {
    accountIds.add(acc.Id);
}
Contact[] relatedContacts = [SELECT Id FROM Contact WHERE AccountId IN:accountIds];
update relatedContacts;

Tip: Use bulk queries and DML outside the loop to handle records together.

2. Leverage Collections

Use collections like List, Set, and Map to store data temporarily during loop execution. This allows you to process data in bulk later, keeping your code within limits.


Example:

apex

CopyEdit



Map<Id, List<Contact>> accountContactMap = new Map<Id, List<Contact>>();

for(Contact c : contactList) {
    if(!accountContactMap.containsKey(c.AccountId)) {
        accountContactMap.put(c.AccountId, new List<Contact>());
    }
    accountContactMap.get(c.AccountId).add(c);
}

Using collections not only avoids redundant processing but also improves readability and scalability.


  1. Use break & continue wisely

Don’t process more data than necessary. Use a break to exit a loop when you’ve achieved your goal, or continue to skip unnecessary iterations.


Example:

apex

CopyEdit



for(Integer i = 0; i < largeList.size(); i++) {
    if(conditionToSkip) {
        continue;
    }
    // Your logic
    if(conditionToStopEarly) {
        break;
    }
}

  1. Minimize Nested Loops

Nested loops can multiply the number of iterations, consuming limits quickly. Replace them with single loops using collections like Map or Set to improve efficiency.


Bad Example:

apex

CopyEdit



for(Account acc : accountList) {
    for(Contact c : contactList) {
        if(c.AccountId == acc.Id) {
            // do something
        }
    }
}

Good Example:

apex

CopyEdit



Map<Id, List<Contact>> accountContactMap = new Map<Id, List<Contact>>();
for(Contact c : contactList) {
    if(!accountContactMap.containsKey(c.AccountId)) {
        accountContactMap.put(c.AccountId, new List<Contact>());
    }
    accountContactMap.get(c.AccountId).add(c);
}

for(Account acc : accountList) {
    if(accountContactMap.containsKey(acc.Id)) {
        // do something with related contacts
    }
}

  1. Keep Loops Simple & Readable

Even efficient code should be easy to understand. Avoid adding too much logic inside loops; extract complex logic into helper methods.

Example:

apex

CopyEdit



for(Opportunity opp : oppList) {
    processOpportunity(opp);
}

private static void processOpportunity(Opportunity opp) {
    // Business logic here
}

Additional Apex Coding Practices to Remember

  • Prefer for loops over while when the count is known.

  • Avoid looping over very large datasets; use Batch Apex for data volume.

  • Test your loop-heavy code with large datasets to ensure you remain within limits.

  • Regularly review and refactor loops as business logic changes.


Conclusion

Efficient apex loop handling is critical for writing scalable and reliable Salesforce Apex Code. Following apex best practices helps keep your code robust, maintainable, and governor-limit friendly.

By structuring loops carefully, bulkifying SOQL/DML, using collections, and keeping logic clean, you’ll write Apex code that not only works but performs well in production.


Struggling with Apex code or a messy Salesforce setup?


Whether it’s performance issues, customizations gone wrong, or planning a smarter CRM, Cloud Science Labs is here to help.


Email us at digital@cloudsciencelabs.com and get your new Salesforce setup or existing one back on track. Want more tips on apex coding practice? Follow our blog and stay updated on best practices to keep your Salesforce projects running smoothly.

 
 
 

Comments


bottom of page