GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • PMD Source Code Analyzer Project
  • Nav
  • Download
  • GitHub
  • Edit on GitHub

This view

  • Original page
  • New address

GeezerVison is showing docs.pmd-code.org — Performance | PMD Source Code Analyzer

 
  • PMD 7.31.0-SNAPSHOT
  • Release date: 28-December-2026
  • About
    • Home
    • Release notes
    • Getting help
    • Release policies
    • Support lifecycle
    • Security
  • User Documentation
    • Migration Guide for PMD 7
    • Installation and basic CLI usage
    • Making rulesets
    • Configuring rules
    • Best practices
    • Suppressing warnings
    • Incremental analysis
    • PMD CLI reference
    • PMD Report formats
    • 3rd party rulesets
    • Signed Releases
    • CPD reference
      • Copy-paste detection
      • CPD Report formats
    • Extending PMD
      • Introduction to writing rules
      • Your first rule
      • XPath rules
      • Java rules
      • Rule designer reference
      • Defining rule properties
      • Rule guidelines
      • Testing your rules
      • Creating (XML) dump of the AST
    • Tools / Integrations
      • Maven PMD Plugin
      • Gradle
      • Ant
      • PMD Java API
      • bld PMD Extension
      • CI integrations
      • IDE Plugins
      • Other Tools / Integrations
  • Rule Reference
    • Apex Rules
      • Index
      • Best Practices
      • Code Style
      • Design
      • Documentation
      • Error Prone
      • Performance
      • Security
    • HTML Rules
      • Index
      • Best Practices
    • Java Rules
      • Index
      • Best Practices
      • Code Style
      • Design
      • Documentation
      • Error Prone
      • Multithreading
      • Performance
      • Security
    • Java Server Pages Rules
      • Index
      • Best Practices
      • Code Style
      • Design
      • Error Prone
      • Security
    • JavaScript Rules
      • Index
      • Best Practices
      • Code Style
      • Error Prone
      • Performance
    • Kotlin Rules
      • Index
      • Best Practices
      • Error Prone
    • Maven POM Rules
      • Index
      • Error Prone
    • Modelica Rules
      • Index
      • Best Practices
    • PLSQL Rules
      • Index
      • Best Practices
      • Code Style
      • Design
      • Error Prone
    • Salesforce Visualforce Rules
      • Index
      • Security
    • Scala Rules
      • Index
    • Swift Rules
      • Index
      • Best Practices
      • Error Prone
    • Velocity Template Language (VTL) Rules
      • Index
      • Best Practices
      • Design
      • Error Prone
    • WSDL Rules
      • Index
    • XML Rules
      • Index
      • Best Practices
      • Error Prone
    • XSL Rules
      • Index
      • Code Style
      • Performance
  • Language-Specific Documentation
    • Overview
    • Language configuration
    • Apex
    • C/C++
    • C#
    • CSS
    • Coco
    • Dart
    • Fortran
    • Gherkin
    • Go
    • HTML
    • Java
    • JavaScript / TypeScript
    • JSP
    • Julia
    • Kotlin
    • Lua
    • Matlab
    • Modelica
    • Objective-C
    • Perl
    • PHP
    • PLSQL
    • Python
    • Ruby
    • Rust
    • Scala
    • Swift
    • T-SQL
    • Visualforce
    • Velocity Template Language (VTL)
    • XML and XML dialects
  • Developer Documentation
    • Contributing
      • Contributing
      • Developer resources
      • Newcomers' Guide
      • Writing documentation
    • Building PMD
      • General Info
      • Building PMD from source
      • Building PMD with IntelliJ IDEA
      • Building PMD with Eclipse IDE
      • Building PMD with VS Code IDE
      • Building PMD with Netbeans IDE
    • Roadmap
    • GitHub Actions Workflows
    • How PMD works
    • Logging
    • Pmdtester
    • Rule Deprecation Policy
    • Major contributions
      • Rule Guidelines
      • Adding a new dialect
      • Adding a new language (JavaCC)
      • Adding a new language (ANTLR)
      • Adding a new CPD language
    • Experimental features
      • List of experimental Features
  • Project documentation
    • Trivia about PMD
      • PMD in the press
      • Products & books related to PMD
      • Similar projects
      • What does 'PMD' mean?
    • Logo
    • FAQ
    • License
    • Credits
    • Old Release Notes
      • Release Notes PMD 7.x
      • Detailed Release Notes PMD 7.0.0
      • Release Notes PMD 6.x
      • Release Notes PMD 5.x
      • Release Notes PMD 4.x and earlier
    • Decisions
    • Project management
      • Infrastructure
      • Release process
      • Merging pull requests
      • Main Landing page

Performance

Rules that flag suboptimal code.
Table of Contents

AvoidDebugStatements

Since: PMD 6.36.0

Priority: Medium (3)

Debug statements contribute to longer transactions and consume Apex CPU time even when debug logs are not being captured.

When possible make use of other debugging techniques such as the Apex Replay Debugger and Checkpoints that could cover most use cases.

For other valid use cases that the statement is in fact valid make use of the @SuppressWarnings annotation or the //NOPMD comment.

This rule is defined by the following XPath expression:

//MethodCallExpression[lower-case(@FullMethodName)='system.debug']

Example(s):

public class Foo {
    public void bar() {
        Account acc = [SELECT Name, Owner.Name FROM Account LIMIT 1];
        System.debug(accs); // will get reported
    }

    @SuppressWarnings('PMD.AvoidDebugStatements')
    public void baz() {
        try {
            Account myAccount = bar();
        } catch (Exception e) {
            System.debug(LoggingLevel.ERROR, e.getMessage()); // good to go
        }
    }
}

Use this rule by referencing it:

<rule ref="category/apex/performance.xml/AvoidDebugStatements" />

AvoidNonRestrictiveQueries

Since: PMD 7.4.0

Priority: Medium (3)

When working with very large amounts of data, unfiltered SOQL or SOSL queries can quickly cause governor limit exceptions.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.performance.AvoidNonRestrictiveQueriesRule

Example(s):

public class Something {
    public static void main( String[] as ) {
        Account[] accs1 = [ select id from account ];  // Bad
        Account[] accs2 = [ select id from account limit 10 ];  // better

        List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead]; // bad
    }
}

Use this rule by referencing it:

<rule ref="category/apex/performance.xml/AvoidNonRestrictiveQueries" />

EagerlyLoadedDescribeSObjectResult

Since: PMD 6.40.0

Priority: Medium (3)

This rule finds DescribeSObjectResults which could have been loaded eagerly via SObjectType.getDescribe().

When using SObjectType.getDescribe() or Schema.describeSObjects() without supplying a SObjectDescribeOptions, implicitly it will be using SObjectDescribeOptions.DEFAULT and then all child relationships will be loaded eagerly regardless whether this information is needed or not. This has a potential negative performance impact. Instead SObjectType.getDescribe(options) or Schema.describeSObjects(SObjectTypes, options) should be used and a SObjectDescribeOptions should be supplied. By using SObjectDescribeOptions.DEFERRED the describe attributes will be lazily initialized at first use.

Lazy loading DescribeSObjectResult on picklist fields is not always recommended. The lazy loaded describe objects might not be 100% accurate. It might be safer to explicitly use SObjectDescribeOptions.FULL in such a case. The same applies when you need the same DescribeSObjectResult to be consistent across different contexts and API versions.

Properties:

  • noDefault: The behavior of SObjectDescribeOptions.DEFAULT changes from API Version 43 to 44: With API Version 43, the attributes are loaded eagerly. With API Version 44, they are loaded lazily. Simply using SObjectDescribeOptions.DEFAULT doesn’t automatically make use of lazy loading. (unless “Use Improved Schema Caching” critical update is applied, SObjectDescribeOptions.DEFAULT does fallback to lazy loading) With this property enabled, such usages are found. You might ignore this, if you can make sure, that you don’t run a mix of API Versions.

This rule is defined by the following XPath expression:

//MethodCallExpression
    [
        lower-case(@MethodName) = "getdescribe" and ReferenceExpression[@SObjectType = true()]
        or lower-case(@MethodName) = "describesobjects"
    ]
    [not(VariableExpression/ReferenceExpression
            [lower-case(@Name) = ("sobjectdescribeoptions", "schema.sobjectdescribeoptions", "fielddescribeoptions", "schema.fielddescribeoptions")]
         )
    ]
|
//ReferenceExpression
    [$noDefault = true()]
    [lower-case(@Name) = ("sobjectdescribeoptions", "schema.sobjectdescribeoptions")]
    [parent::VariableExpression[lower-case(@Image) = "default"]]

Example(s):

public class Foo {
    public static void bar(List<Account> accounts) {
        if (Account.SObjectType.getDescribe(SObjectDescribeOptions.DEFERRED).isCreateable()) {
            insert accounts;
        }
    }
}

This rule has the following properties:

Name Default Value Description
noDefault false Do not allow SObjectDescribeOptions.DEFAULT option to ensure consistent results no matter where getDescribe is called

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/performance.xml/EagerlyLoadedDescribeSObjectResult" />

Use this rule and customize it:

<rule ref="category/apex/performance.xml/EagerlyLoadedDescribeSObjectResult">
    <properties>
        <property name="noDefault" value="false" />
    </properties>
</rule>

OperationWithHighCostInLoop

Since: PMD 7.0.0

Priority: Medium (3)

This rule finds method calls inside loops that are known to be likely a performance issue. These methods should be called only once before the loop.

Schema class methods like Schema.getGlobalDescribe() and Schema.describeSObjects() might be slow depending on the size of your organization. Calling these methods repeatedly inside a loop creates a potential performance issue.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.performance.OperationWithHighCostInLoopRule

Example(s):

public class GlobalDescribeExample {
    // incorrect example
    public void getGlobalDescribeInLoop() {
        Set<String> fieldNameSet = new Set<String> {'Id'};
        for (String fieldNameOrDefaultValue : fieldNameOrDefaultValueList) {
            // Schema.getGlobalDescribe() should be called only once before the for-loop
            if (Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap().containsKey(fieldNameOrDefaultValue.trim())) {
                fieldNameSet.add(fieldNameOrDefaultValue);
            }
        }
    }

    // corrected example
    public void getGlobalDescribeInLoopCorrected() {
        Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
        Set<String> fieldNameSet = new Set<String> {'Id'};
        for (String fieldNameOrDefaultValue : fieldNameOrDefaultValueList) {
            if (fieldMap.containsKey(fieldNameOrDefaultValue.trim())) {
                fieldNameSet.add(fieldNameOrDefaultValue);
            }
        }
    }
}
public class DescribeSObjectsExample {
    // incorrect example
    public void describeSObjectsInLoop() {
        Set<String> fieldNameSet = new Set<String> {'Id'};
        for (String fieldNameOrDefaultValue : fieldNameOrDefaultValueList) {
            Schema.DescribeSObjectResult dsr = Account.sObjectType.getDescribe();
            if (Schema.describeSObjects(new List<String> { sObjectType })[0].fields.getMap().containsKey(fieldNameOrDefaultValue.trim())) {
                fieldNameSet.add(fieldNameOrDefaultValue);
            }
        }
    }

    // corrected example
    public void describeSObjectsInLoop() {
        Map<String, Schema.SObjectField> fieldMap = Schema.describeSObjects(new List<String> { 'Account' })[0].fields.getMap();
        Set<String> fieldNameSet = new Set<String> {'Id'};
        for (String fieldNameOrDefaultValue : fieldNameOrDefaultValueList) {
            if (fieldMap.containsKey(fieldNameOrDefaultValue.trim())) {
                fieldNameSet.add(fieldNameOrDefaultValue);
            }
        }
    }
}

Use this rule by referencing it:

<rule ref="category/apex/performance.xml/OperationWithHighCostInLoop" />

OperationWithLimitsInLoop

Since: PMD 6.29.0

Priority: Medium (3)

Database class methods, DML operations, SOQL queries, SOSL queries, Approval class methods, Email sending, async scheduling or queueing within loops can cause governor limit exceptions. Instead, try to batch up the data into a list and invoke the operation 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.OperationWithLimitsInLoopRule

Example(s):

public class Something {
    public void databaseMethodInsideOfLoop(List<Account> accounts) {
        for (Account a : accounts) {
            Database.insert(a);
        }
    }

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

    public void soqlInsideOfLoop() {
        for (Integer i = 0; i < 10; i++) {
            List<Account> accounts = [SELECT Id FROM Account];
        }
    }

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

    public void messageInsideOfLoop() {
        for (Integer i = 0; i < 10; i++) {
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
        }
    }

    public void approvalInsideOfLoop(Account[] accs) {
        for (Integer i = 0; i < 10; i++) {
            Account acc = accs[i];
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setObjectId(acc.Id);
            Approval.process(req);
            Approval.lock(acc);
            Approval.unlock(acc);
        }
    }

    public void asyncInsideOfLoop() {
        for (Integer i = 0; i < 10; i++) {
            System.enqueueJob(new MyQueueable());
            System.schedule('x', '0 0 0 1 1 ?', new MySchedule());
            System.scheduleBatch(new MyBatch(), 'x', 1);
        }
    }
}

Use this rule by referencing it:

<rule ref="category/apex/performance.xml/OperationWithLimitsInLoop" />
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.