Sub topic 10
CPU Time and Heap Size
This chapter assumes you can read basic Apex, know the List, Set and Map collections, and have already moved SOQL and DML out of loops. Those two fixes handle most limit failures. CPU time and heap size are the limits that remain once your queries and DML are bulkified.
What the two limits measure
CPU time is the time the Salesforce application servers spend running your code in one transaction. In synchronous Apex the limit is 10,000 ms. In asynchronous Apex it is 60,000 ms. Time spent waiting for the database or for a callout does not count. Time spent in your loops, string handling, and in declarative automation that runs in the same transaction does count.
Heap size is the memory your variables use at one moment in the transaction. The synchronous limit is 6 MB. The asynchronous limit is 12 MB. These are the values documented at the time of writing, so check the current Apex Developer Guide before relying on them.
| Limit | Synchronous | Asynchronous | Exception thrown |
|---|---|---|---|
| CPU time | 10,000 ms | 60,000 ms | `System.LimitException: Maximum CPU time exceeded` |
| Heap size | 6 MB | 12 MB | `System.LimitException: Apex heap size too large` |
Neither exception can be caught with try/catch. The transaction stops and rolls back.
Where CPU time goes
Bulkified code can still use too much CPU. Common causes are:
- Nested loops. Two loops of 200 items each run the inner body 40,000 times.
- Searching a List inside a loop with
containsorindexOf. Each search scans the list. - Heavy string work, such as building a long string with
+in a loop, or serializing large JSON. - Many triggers, flows and workflow rules firing on the same object in one transaction.
The usual fix for nested loops is to replace the inner loop with a Map lookup.
// Slow: the inner loop runs once for every Contact
for (Contact c : contacts) {
for (Account a : accounts) {
if (a.Id == c.AccountId) {
c.Description = a.Industry;
}
}
}// Faster: build the Map once, then do one lookup per Contact
Map<Id, Account> accountsById = new Map<Id, Account>(accounts);
for (Contact c : contacts) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
c.Description = a.Industry;
}
}The first version does work proportional to contacts times accounts. The second does work proportional to contacts plus accounts.
Where heap goes
Heap grows when you hold data you no longer need. Typical causes:
- Querying every field or every row when you use only a few.
- Keeping several copies of the same large List.
- Reading a large file or response body into one String or Blob.
Query only the fields you need. For a large result set, use a SOQL for loop. It retrieves records in chunks of 200 instead of loading the whole result into memory.
Integer missing = 0;
for (List<Account> chunk : [SELECT Id, Industry FROM Account]) {
for (Account a : chunk) {
if (a.Industry == null) {
missing++;
}
}
}
System.debug('Accounts without an industry: ' + missing);Only one chunk of 200 records is held at a time. The total rows retrieved limit still applies.
Measuring before you optimize
Use the Limits class to see where consumption rises. Print the CPU time before and after a suspect block.
Integer cpuBefore = Limits.getCpuTime();
Integer heapBefore = Limits.getHeapSize();
// ... the code you suspect ...
System.debug('CPU used (ms): ' + (Limits.getCpuTime() - cpuBefore));
System.debug('Heap used (bytes): ' + (Limits.getHeapSize() - heapBefore));When optimizing is not enough
Some work is large by nature. Asynchronous Apex gives a higher CPU and heap ceiling. Batch Apex goes further: each execute call is a separate transaction with its own limits, so the total work can be far larger than any single transaction allows. The next chapter covers these tools.
Exercise
A trigger passes the bulk test with 200 records but fails with "Maximum CPU time exceeded" in production. It has no SOQL or DML inside loops. Name two likely causes and one way to confirm which block is responsible.
Show answer
Likely causes: nested loops or list searches that scale with data volume, and other automation (flows, other triggers) running in the same transaction. To confirm, read Limits.getCpuTime() before and after each suspect block, print the difference with System.debug, and compare the results. The debug log's cumulative limits section also shows total CPU used.
Exercise
Why does a SOQL for loop help with heap size, and what limit does it not remove?
Show answer
It retrieves records in chunks of 200 instead of loading the full result into one List, so less memory is held at once. It does not remove the limit on total rows retrieved by SOQL in the transaction.