Sub topic 10
CPU Time and Heap Size
This chapter covers the two limits that SOQL and DML fixes do not solve: CPU time and heap size. It assumes you can read Apex, know List, Set and Map, and have already moved queries and DML out of loops. The limits quoted here are the commonly documented synchronous and asynchronous values. Check the current Apex Developer Guide for exact numbers, because Salesforce can change them.
Why these two limits are different
SOQL and DML limits count statements. You can see them in the code, and a loop makes them obvious. CPU time and heap size measure resources. Code that issues one query and one DML statement can still fail because it burns too much processing time or holds too much data in memory.
| Limit | Synchronous | Asynchronous | What it measures |
|---|---|---|---|
| CPU time | 10,000 ms | 60,000 ms | Time Apex code spends on the Salesforce application servers in one transaction |
| Heap size | 6 MB | 12 MB | Memory used by variables, collections and objects at one moment |
Exceeding either limit throws an uncatchable System.LimitException. The whole transaction rolls back. You cannot recover with try/catch, so you have to stay below the limit by design.
CPU time
What counts
CPU time is the time the Apex code and the work that runs with it spend executing in one transaction. It includes:
- Apex code execution, including loops, string handling and method calls.
- Triggers, workflow-style automation, flows and process logic that run in the same transaction.
- Validation rules, formula evaluation and other declarative logic fired by your DML.
It does not include time spent waiting on the database for a query, time spent on callouts, or time the transaction waits in a queue. A slow query hurts you in other ways, but it does not consume CPU time.
This matters because the limit is shared across everything in the transaction. A trigger that uses 2 seconds is not alone. A flow, another trigger and a managed package on the same record save add to the same 10,000 ms.
Where CPU time goes
CPU time is usually consumed by one of these patterns:
- Nested loops. Two loops over 200 records each run 40,000 iterations.
- Searching a List inside a loop.
list.contains()scans the list, so calling it per record is a hidden nested loop. - Heavy string work, such as repeated concatenation, large
String.formatcalls or regular expressions on big values. - JSON serialization and deserialization of large structures.
- Repeated recalculation of the same value inside a loop.
- Many triggers and automations all firing on the same object.
Replace nested loops with a Map
The nested-loop version below matches each Contact to its Account by scanning a list.
List<Account> accounts = [SELECT Id, Industry FROM Account LIMIT 200];
List<Contact> contacts = [SELECT Id, AccountId FROM Contact LIMIT 200];
// Anti-pattern: for each contact, scan every account
for (Contact c : contacts) {
for (Account a : accounts) {
if (a.Id == c.AccountId) {
c.Description = 'Industry: ' + a.Industry;
}
}
}The work grows with the product of the two list sizes. With a Map the lookup cost per contact is roughly constant.
List<Account> accounts = [SELECT Id, Industry FROM Account LIMIT 200];
List<Contact> contacts = [SELECT Id, AccountId FROM Contact LIMIT 200];
Map<Id, Account> accountsById = new Map<Id, Account>(accounts);
for (Contact c : contacts) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
c.Description = 'Industry: ' + a.Industry;
}
}The same idea applies to List.contains(). If you test membership repeatedly, copy the values into a Set once and call Set.contains().
Set<String> blockedDomains = new Set<String>{ 'example.com', 'test.org' };
List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE Email != null LIMIT 200];
for (Contact c : contacts) {
String domain = c.Email.substringAfter('@').toLowerCase();
if (blockedDomains.contains(domain)) {
c.HasOptedOutOfEmail = true;
}
}Do invariant work once
Anything that gives the same answer on every iteration belongs before the loop.
// Anti-pattern: the describe call and the string are rebuilt for every record
for (Account a : Trigger.new) {
String prefix = Schema.SObjectType.Account.getKeyPrefix();
a.Description = prefix + '-' + a.Name;
}String prefix = Schema.SObjectType.Account.getKeyPrefix();
for (Account a : Trigger.new) {
a.Description = prefix + '-' + a.Name;
}Filter early with the query
Do work in SOQL when you can. A WHERE clause that removes rows in the database costs no Apex CPU. Looping over every row and discarding most of them in Apex does cost CPU, and it also loads those rows into the heap.
Measure instead of guessing
Use the Limits class from the previous chapter around a suspect block. This code compares the CPU time before and after.
Integer before = Limits.getCpuTime();
// ... code under test ...
Integer used = Limits.getCpuTime() - before;
System.debug('Block used ' + used + ' ms of ' + Limits.getLimitCpuTime());Debug logs also include a limits summary at the end of each transaction. Run the real scenario with 200 records, because CPU cost often looks harmless with 1 record.
Heap size
What counts
Heap size is the memory your code holds at one moment. It includes every variable, List, Set, Map, SObject and string that is still reachable. The limit applies to the peak, not the total over the transaction. Memory held by a variable that has gone out of scope can be reclaimed.
Fields you query add to the heap. An SObject with 40 fields holds more than one with 3 fields, and a long text area field can be very large.
Common causes of heap errors
- Querying with too many fields or long text fields you do not use.
- Loading a very large result set into a List in one statement.
- Building large strings, such as CSV text or JSON, in memory.
- Keeping several copies of the same data, such as
Trigger.new, a cloned list and a map built from it. - Reading large files or attachments into a
Blob. - Static variables or caches that grow for the whole transaction.
Select only what you need
// Heavier: loads every field you list for every row
List<Account> heavy = [
SELECT Id, Name, Description, BillingStreet, BillingCity, Industry
FROM Account
];
// Lighter: loads only what the logic uses
List<Account> light = [SELECT Id, Industry FROM Account];Use a SOQL for loop for large results
A normal query loads every row into the heap before your code runs. A SOQL for loop retrieves the rows in chunks of 200, so only one chunk is in memory at a time.
Integer total = 0;
for (List<Account> chunk : [SELECT Id, AnnualRevenue FROM Account]) {
for (Account a : chunk) {
if (a.AnnualRevenue != null) {
total += 1;
}
}
}
System.debug('Accounts with revenue: ' + total);This lowers heap use. It does not remove the row limit: a transaction can still retrieve at most 50,000 rows in total across all its queries. It also does not make the loop cheaper in CPU time.
Aggregate in SOQL
If you only need a count or a sum, ask the database for it.
AggregateResult[] results = [
SELECT Industry, COUNT(Id) total
FROM Account
WHERE Industry != null
GROUP BY Industry
];
for (AggregateResult ar : results) {
System.debug(ar.get('Industry') + ': ' + ar.get('total'));
}This returns a few rows instead of thousands of records, which saves both heap and CPU.
Release data you no longer need
When a large collection is finished with, set the variable to null before doing more heavy work in the same scope. Use this when a method builds a large structure early and then moves on to a different task.
List<Account> bigList = [SELECT Id, Name FROM Account LIMIT 20000];
Integer count = bigList.size();
bigList = null; // makes the memory eligible for reclamation
// ... later work now has more heap available ...Do not scatter null assignments everywhere. Use them only where measurement shows a heap problem.
Heap and string building
Building one huge string, such as a CSV export, keeps the whole text in memory. Prefer lists of smaller strings and join them at the end only if you must. Better still, move the export to asynchronous Apex or write it out in chunks.
List<String> lines = new List<String>();
for (Account a : [SELECT Id, Name FROM Account LIMIT 1000]) {
lines.add(a.Id + ',' + a.Name);
}
String csv = String.join(lines, '\n');
System.debug('CSV length: ' + csv.length());Watch the heap
System.debug('Heap: ' + Limits.getHeapSize() + ' of ' + Limits.getLimitHeapSize());Calling this before and after a large step shows how much memory the step adds.
How CPU time and heap interact
The two limits often trade off. Caching query results in a Map saves CPU, because it avoids repeated scans, but it keeps data in the heap. A SOQL for loop saves heap but gives up the ability to look up any record at any time. Choose by measuring which limit you are closer to.
The diagram below summarizes the decision.
When optimizing is not enough
Some jobs are simply too large for one synchronous transaction, such as recalculating every Account or processing a large file. Asynchronous Apex gives each job a higher ceiling: 60,000 ms of CPU and 12 MB of heap. Batch Apex goes further, because each execute call is a separate transaction with its own fresh limits. The next chapter covers Queueable and Batch Apex in detail.
Do not use asynchronous Apex to hide inefficient code. A nested loop that takes 9 seconds synchronously will still waste time asynchronously, and it may hit the higher limit as data grows.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Apex CPU time limit exceeded` with only a few queries | Nested loops, `List.contains()` in a loop, or many automations on one object | Use Maps and Sets, and review other automation on the object |
| Error appears only on large saves | Code that is fine for 1 record but scales with the square of the batch | Test with 200 records and measure with `Limits.getCpuTime()` |
| `Apex heap size too large` on a single query | Too many rows or large fields loaded into a List | Select fewer fields, use a SOQL for loop, or aggregate |
| Heap error while building output | One very large string or Blob held in memory | Build in chunks or move to asynchronous Apex |
| Code catches the exception but the transaction still fails | `LimitException` cannot be caught | Check `Limits` values and stop work before reaching the limit |
| Debug statements make CPU time worse | Heavy string building inside debug calls in loops | Log summaries after the loop, not per record |
Practical checklist
- Test with 200 records in one operation, not 1.
- Replace any loop inside a loop with a Map or Set lookup.
- Move values that do not change out of loops.
- Query only the fields you use, and filter in the
WHEREclause. - Use a SOQL for loop or an aggregate query for large data sets.
- Check
Limits.getCpuTime()andLimits.getHeapSize()around suspect blocks. - Count the other automation on the object. Its CPU time adds to yours.
- Move work to Queueable or Batch Apex only after the code itself is efficient.
Exercise
A trigger on Contact runs one query and one DML statement for a batch of 200 records, so SOQL and DML limits are fine. It still fails with "Apex CPU time limit exceeded". Inside the loop over Trigger.new, it calls accountList.contains(c.AccountId) on a List of 5,000 Ids. Explain why this is expensive and show how to fix it.
Show answer
List.contains() scans the list from the start until it finds a match, so each call can examine up to 5,000 items. Called for 200 contacts, that is up to 1,000,000 comparisons, a hidden nested loop that uses CPU time. The fix is to copy the Ids into a Set once before the loop, for example Set<Id> accountIdSet = new Set<Id>(accountList);, and call accountIdSet.contains(c.AccountId) inside the loop. A Set lookup takes roughly constant time, so the total work grows with the number of contacts only.
Exercise
A method queries SELECT Id, Name, Description, Body__c FROM Case__c for 40,000 rows and fails with "Apex heap size too large", although it stays under the 50,000-row limit. Name two changes that reduce heap use without moving to asynchronous Apex.
Show answer
First, query only the fields the logic needs, and drop large fields such as Description and Body__c if they are unused. Second, replace the single List query with a SOQL for loop (for (List<Case__c> chunk : [SELECT ...])), which loads 200 rows at a time so only one chunk is in memory. Aggregating in SOQL with COUNT or SUM is also valid if the logic only needs totals.