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
Name | Default Value | Description | Multivalued |
---|---|---|---|
cc_categories | Performance | Deprecated Code Climate Categories | yes. Delimiter is ‘|’. |
cc_remediation_points_multiplier | 150 | Deprecated Code Climate Remediation Points multiplier | no |
cc_block_highlighting | false | Deprecated Code Climate Block Highlighting | no |
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
Name | Default Value | Description | Multivalued |
---|---|---|---|
cc_categories | Performance | Deprecated Code Climate Categories | yes. Delimiter is ‘|’. |
cc_remediation_points_multiplier | 150 | Deprecated Code Climate Remediation Points multiplier | no |
cc_block_highlighting | false | Deprecated Code Climate Block Highlighting | no |
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
Name | Default Value | Description | Multivalued |
---|---|---|---|
cc_categories | Performance | Deprecated Code Climate Categories | yes. Delimiter is ‘|’. |
cc_remediation_points_multiplier | 150 | Deprecated Code Climate Remediation Points multiplier | no |
cc_block_highlighting | false | Deprecated Code Climate Block Highlighting | no |