Sub topic 15
Measuring limit usage with the Limits class
This chapter assumes you can write Apex classes and triggers, run SOQL and DML statements, and know that a transaction shares one set of governor limits. You should also know how to move SOQL out of loops using Sets and Maps. Here you will measure how much of each limit your code actually uses.
Why measure
Bulkified code should use a fixed number of queries and DML statements, no matter how many records arrive. You can check that claim by reading the counters Apex keeps for the current transaction. The Limits class exposes them.
Each limit has two static methods:
Limits.getQueries()returns the number of SOQL queries used so far.Limits.getLimitQueries()returns the maximum allowed.
The same pairs exist for other resources, as the table shows.
| Resource | Used so far | Maximum |
|---|---|---|
| SOQL queries | `Limits.getQueries()` | `Limits.getLimitQueries()` |
| Records returned by SOQL | `Limits.getQueryRows()` | `Limits.getLimitQueryRows()` |
| DML statements | `Limits.getDmlStatements()` | `Limits.getLimitDmlStatements()` |
| Records changed by DML | `Limits.getDmlRows()` | `Limits.getLimitDmlRows()` |
| CPU time (ms) | `Limits.getCpuTime()` | `Limits.getLimitCpuTime()` |
| Heap size (bytes) | `Limits.getHeapSize()` | `Limits.getLimitHeapSize()` |
The values depend on the context. A synchronous transaction allows 100 SOQL queries, and an asynchronous one allows 200. Read the maximum from Limits and do not hard-code it.
Measuring a handler
The most useful pattern is to take a reading before and after a block of work and compare. This example reuses the Opportunity handler idea from earlier chapters.
public with sharing class LimitProbe {
public static void report(String label, Integer queriesBefore, Integer dmlBefore) {
Integer queries = Limits.getQueries() - queriesBefore;
Integer dml = Limits.getDmlStatements() - dmlBefore;
System.debug(
label + ': ' + queries + ' queries, ' + dml + ' DML statements. '
+ 'Total queries ' + Limits.getQueries() + '/' + Limits.getLimitQueries()
+ ', CPU ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime() + ' ms'
);
}
}Call it around the work you want to inspect:
Integer q = Limits.getQueries();
Integer d = Limits.getDmlStatements();
OpportunityTriggerHandler.createFollowUpTasks(Trigger.new, Trigger.oldMap);
LimitProbe.report('createFollowUpTasks', q, d);Open the debug log and look for the USER_DEBUG line. For a bulkified handler, the query and DML counts stay the same whether the trigger receives 1 record or 200.
Using measurements in tests
A test can turn the same readings into an assertion. Add this to the bulk test from the testing chapter, so a loop that sneaks in later fails the build.
@IsTest
private class OpportunityLimitsTest {
@IsTest
static void usesFixedNumberOfStatementsFor200Records() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Limits ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
Test.startTest();
update opps;
Integer dmlStatements = Limits.getDmlStatements();
Test.stopTest();
System.assert(dmlStatements <= 3,
'Expected a small, fixed number of DML statements but saw ' + dmlStatements);
}
}Test.startTest() resets the counters, so the reading covers only the update and its trigger work. The update statement counts as one. The handler's insert tasks adds a second, which leaves room for a small amount of extra work.
Common mistakes
- Comparing against a hard-coded number. Use
Limits.getLimitQueries(), because the maximum changes between synchronous and asynchronous contexts. - Measuring with one record. A loop with a query inside looks fine at one record. Use 200 records.
- Leaving debug calls in production code. Each call costs CPU time, and
System.debugoutput can be truncated in large logs. Remove the probes when you finish, or keep them in tests. - Reading too late. Counters are cumulative for the whole transaction. Without a "before" reading, you cannot tell which code used the limit.
Exercise
A trigger handler runs with 200 records in a test. Before the handler call, Limits.getQueries() returns 4. After the call, it returns 6. What does this tell you, and what would make you suspect a loop problem?
Show answer
The handler used 2 queries (6 minus 4). If the count is the same at 1 record and at 200 records, the handler is bulkified. If the count grows with the number of records, for example 204 after 200 records, a SOQL query is running inside a loop.