Rows counted with size() instead of SELECT COUNT()
ID |
apex.performance.soql_count_instead_size |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Performance |
Language |
Apex |
Description
Reports a SOQL query whose result is only counted, by calling size() directly on the query.
Rationale
The query returns every matching row into the heap before size() looks at how many there are: on a large object that is the 6 MB synchronous heap limit and a QueryException: Too many query rows: 50001 for a number the database could have returned on its own. SELECT COUNT() is answered by the index and costs one row of heap regardless of how many records match.
The following code illustrates the pattern detected by this rule:
public class RowCounting {
public Integer countAccounts(String name) {
// FLAGGED: Rows counted with size() instead of SELECT COUNT()
Integer total = [SELECT Id FROM Account WHERE Name = :name].size();
return total;
}
public Integer countAccountsAggregate(String name) {
Integer total = [SELECT COUNT() FROM Account WHERE Name = :name];
return total;
}
public Integer countLoaded(String name) {
List<Account> accts = [SELECT Id, Name FROM Account WHERE Name = :name];
return accts.size();
}
}