Apex performance best practices

This article is based on the PMD documentation article. See the original article on the PMD site: PMD: performance best practices.

Below are the generally accepted best practices. 

AvoidDmlStatementsInLoops

Avoid DML statements inside loops to avoid hitting the DML governor limit. Instead, try to batch up the data into a list and invoke your DML once on that list of data outside the loop.

This rule is defined by the following Java class: 

net.sourceforge.pmd.lang.apex.rule.performance.AvoidDmlStatementsInLoopsRule

Example

public class Something {
    public void foo() {
        for (Integer i = 0; i < 151; i++) {
            Account account;
            // ...
            insert account;
        }
    }
}

Properties

NameDefault ValueDescriptionMultivalued
cc_categoriesPerformanceDeprecated Code Climate Categoriesyes. Delimiter is ‘|’.
cc_remediation_points_multiplier150Deprecated Code Climate Remediation Points multiplierno
cc_block_highlightingfalseDeprecated Code Climate Block Highlightingno

AvoidSoqlInLoops

New objects created within loops should be checked to see if they can created outside them and reused.

This rule is defined by the following Java class: 

net.sourceforge.pmd.lang.apex.rule.performance.AvoidSoqlInLoopsRule

Example

public class Something {
    public static void main( String as[] ) {
        for (Integer i = 0; i < 10; i++) {
            List<Account> accounts = [SELECT Id FROM Account];
        }
    }
}

Properties

NameDefault ValueDescriptionMultivalued
cc_categoriesPerformanceDeprecated Code Climate Categoriesyes. Delimiter is ‘|’.
cc_remediation_points_multiplier150Deprecated Code Climate Remediation Points multiplierno
cc_block_highlightingfalseDeprecated Code Climate Block Highlightingno

AvoidSoslInLoops

Sosl calls within loops can cause governor limit exceptions.

This rule is defined by the following Java class: 

net.sourceforge.pmd.lang.apex.rule.performance.AvoidSoslInLoopsRule

Example

public class Something {
    public static void main( String as[] ) {
        for (Integer i = 0; i < 10; i++) {
            List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead];
        }
    }
}

Properties

NameDefault ValueDescriptionMultivalued
cc_categoriesPerformanceDeprecated Code Climate Categoriesyes. Delimiter is ‘|’.
cc_remediation_points_multiplier150Deprecated Code Climate Remediation Points multiplierno
cc_block_highlightingfalseDeprecated Code Climate Block Highlightingno

What's here


Related content

 PMD: performance best practices




Last modified on Jul 14, 2020