Sub topic 8
Checking Consumption with the Limits Class
This chapter assumes you can write Apex classes and triggers, run SOQL and DML, and use List, Set and Map. You should also know what a governor limit is and roughly which ones exist (SOQL queries, DML statements, rows, CPU time, heap).
What the Limits class gives you
Governor limits only help you if you can see how close a transaction is to them. The built-in Limits class reports this from inside running code. It has two kinds of methods:
Limits.getX()returns how much of resource X the current transaction has used so far.Limits.getLimitX()returns the maximum allowed for X in the current context.
Here X stands for the resource: Queries, DmlStatements, DmlRows, QueryRows, CpuTime, HeapSize and others. The maximum is not the same everywhere. Synchronous and asynchronous transactions have different ceilings for some limits, such as heap size and the number of SOQL queries. That is why you should read getLimitX() instead of hard-coding a number.
Printing a usage snapshot
This snippet writes the four most useful measurements to the debug log:
System.debug('SOQL queries: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
System.debug('DML statements: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements());
System.debug('CPU time (ms): ' + Limits.getCpuTime() + ' of ' + Limits.getLimitCpuTime());
System.debug('Heap size (bytes): ' + Limits.getHeapSize() + ' of ' + Limits.getLimitHeapSize());You can run it in Anonymous Apex, or paste it into a class at the point you want to measure. Each line prints a "used of maximum" pair, so you can tell at a glance how much headroom is left.
Measuring a piece of code
A single snapshot shows the running total for the whole transaction. To find out what one block of code costs, take a reading before and after, then subtract.
Integer queriesBefore = Limits.getQueries();
List<Account> accounts = [SELECT Id, Industry FROM Account LIMIT 50];
Integer queriesUsed = Limits.getQueries() - queriesBefore;
System.debug('This block used ' + queriesUsed + ' SOQL queries.');The same approach works for DML statements, CPU time and heap. It is a quick way to confirm that a rewrite from per-record queries to a Map-based lookup did what you expected. The anti-pattern trigger from earlier chapters would show one query per Contact in the batch. The bulkified version would show one query in total.
Where to look for the numbers
The Limits class is the source of truth at runtime. For the published values, use the Apex Developer Guide section on execution governors and limits. Salesforce changes some limits between releases, so do not copy numbers from old articles into your code.
You can also see limit usage without writing any code. When you run a test or open a debug log, the log ends with a CUMULATIVE_LIMIT_USAGE section. It lists how much of each limit the transaction used, grouped by namespace.
Common mistakes
- Hard-coding limits. Writing
if (Limits.getQueries() > 90)bakes in a number that may be wrong in another context. Compare againstLimits.getLimitQueries()instead. - Reading CPU time as exact.
Limits.getCpuTime()is useful for comparing two versions of code, but small differences between runs are normal. Look for large changes. - Leaving debug statements in hot paths.
System.debugcalls inside a loop that runs thousands of times add their own CPU cost and fill the log. Remove them or measure outside the loop. - Using limit checks to hide a design problem. If you need
Limitsto decide whether a query is safe inside a loop, move the query out of the loop instead.
Using Limits in tests
Limit values are also available in test code, which lets you turn a performance expectation into an assertion. Combined with a test that inserts 200 records, this catches a regression the moment someone adds a query to a loop.
@IsTest
private class QueryBudgetTest {
@IsTest
static void insertStaysWithinQueryBudget() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Budget Test ' + i));
}
Test.startTest();
insert accounts;
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
System.assert(queriesUsed < 10,
'Expected fewer than 10 queries but used ' + queriesUsed);
}
}Test.startTest() gives the code under test a fresh set of limits, so the reading reflects only the insert and its triggers. The threshold of 10 is an example. Pick a budget that matches what your own code should need.
Exercise
A teammate wants to protect a loop by writing if (Limits.getQueries() < 100) { ... query ... }. Give two reasons this is a weak approach, and say what to do instead.
Show answer
First, the number 100 is hard-coded, but the real maximum depends on the context, so the check can be wrong. Second, the check only skips the query once the budget is almost gone, so some records go unprocessed and the real cause, a query per record, remains. Instead, collect the Ids in a Set, run one query into a Map outside the loop, and use Limits.getQueries() before and after to confirm that only one query ran.
Exercise
How do you measure how many DML statements one block of code uses?
Show answer
Store Limits.getDmlStatements() in a variable before the block, run the block, then subtract the stored value from Limits.getDmlStatements() read after it.