Sub topic 16
Heap size and collection limits
This chapter assumes you can write Lists, Sets, and Maps, query records with SOQL, and read the grouping and bulkification patterns from earlier chapters. Here you learn what limits apply to collections, how to measure memory use, and how to lower it.
No element cap, but a memory budget
Apex does not cap how many elements a List, Set, or Map can hold. The practical cap is the heap, which is the memory your transaction uses for variables, collections, and the objects inside them. Salesforce enforces these heap limits per transaction:
| Execution context | Heap limit |
|---|---|
| Synchronous (triggers, controllers, anonymous Apex) | 6 MB |
| Asynchronous (Queueable, Batch, `@future`, Schedulable) | 12 MB |
If a transaction goes over its limit, Apex throws System.LimitException: Apex heap size too large. You cannot catch this exception with try/catch, so the transaction ends and rolls back. You have to design code that stays under the limit.
Collections affect the heap in three ways:
- Each element takes space. A List of 50,000 Contact records with ten fields each takes far more than a List of 50,000 Ids.
- Copies take space.
clone(),new List<...>(otherList),Map.values(), andMap.keySet()each create a new collection, even though the elements are shared references (see the previous chapter). - Static variables and long-lived fields stay allocated for the whole transaction. Local variables can be freed once they go out of scope.
Related limits that collections run into
Collections are usually how you hit other governor limits too. These are the synchronous per-transaction values:
| Limit | Value | How collections relate |
|---|---|---|
| Records returned by SOQL | 50,000 | A query result stored in a List counts against this and against the heap |
| SOQL queries issued | 100 | Query once, then look up in a Map |
| Records processed by DML | 10,000 | A List passed to `insert` or `update` counts every element |
| Heap size | 6 MB | Every collection and its elements |
| CPU time | 10,000 ms | Nested loops over large collections burn CPU |
| SOQL statement length | 100,000 characters | A very large literal `IN` list can exceed this, but a bind variable does not |
Check the current Apex limits documentation for your org's release, because Salesforce adjusts some values.
Measuring heap use
The Limits class reports usage while code runs. Limits.getHeapSize() returns the bytes used so far, and Limits.getLimitHeapSize() returns the ceiling for the current context.
Integer before = Limits.getHeapSize();
List<String> values = new List<String>();
for (Integer i = 0; i < 5000; i++) {
values.add('Record number ' + i);
}
Integer after = Limits.getHeapSize();
System.debug('Limit: ' + Limits.getLimitHeapSize() + ' bytes');
System.debug('Used by the list: ' + (after - before) + ' bytes');
System.debug('Elements: ' + values.size());Run this in anonymous Apex and read the debug log. The exact number differs between releases, so do not hard-code it. Use the measurement to compare approaches, such as a List of full records against a Map of Ids to a smaller value.
Why large query results cause trouble
The most common heap failure is storing a full query result in a variable.
// Risky for large tables: every row and every field is held at once.
List<Account> all = [SELECT Id, Name, Description, BillingStreet FROM Account];
Map<Id, Account> byId = new Map<Id, Account>(all);The List holds the records. The Map holds references to the same records, plus its own structure. Long text fields such as Description are the largest part of the cost. If the table has 40,000 rows with long descriptions, the heap fills quickly even though the row count is under 50,000.
There are three ways to reduce the cost.
Select only the fields you use
Each extra field adds memory for every row. Remove fields that your code never reads.
Filter in SOQL, not in a loop
Move conditions into the WHERE clause. Fewer rows come back, so fewer objects are allocated.
List<Account> active = [
SELECT Id, Name
FROM Account
WHERE IsActive__c = true
LIMIT 10000
];This example assumes your org has a custom checkbox field named IsActive__c. Replace it with a field that exists in your org.
Use a SOQL for loop to process in chunks
A SOQL for loop does not load the whole result into one variable. Apex fetches the records in batches of 200 as the loop advances, so only one batch needs to be in memory at a time.
Integer processed = 0;
Set<String> distinctNames = new Set<String>();
for (List<Account> batch : [SELECT Id, Name FROM Account]) {
for (Account a : batch) {
distinctNames.add(a.Name);
processed++;
}
}
System.debug('Rows seen: ' + processed);
System.debug('Distinct names: ' + distinctNames.size());
System.debug('Heap used: ' + Limits.getHeapSize());The loop variable is a List<Account>, so you get 200 records per iteration. Only distinctNames grows over time, and it stores names instead of full records. This pattern keeps your own state small even when the result set is large. The total number of rows read still counts against the 50,000-row query limit.
Keep the collections you build small
Choose what you store, not only what you query.
- Store Ids when you only need to test membership. A
Set<Id>is smaller than aMap<Id, Account>holding the same keys. - Store a value, not a record. If you only need an account's name by Id, a
Map<Id, String>takes less memory than aMap<Id, Account>, because the unused fields are not retained. - Avoid unnecessary copies. Do not call
new List<Contact>(contacts)just to read the data. Callclone()or build a copy only when you need to modify the copy independently. - Release large collections early. After you finish with a big local collection, you can set it to
nullso its memory can be reclaimed before the transaction ends. This helps mainly in long methods. It has no effect on a collection that another variable still references.
List<Contact> contacts = [SELECT Id, AccountId FROM Contact LIMIT 5000];
// Keep only what later code needs.
Map<Id, Integer> contactCountByAccount = new Map<Id, Integer>();
for (Contact c : contacts) {
Integer current = contactCountByAccount.get(c.AccountId);
contactCountByAccount.put(c.AccountId, current == null ? 1 : current + 1);
}
contacts = null; // The full records are no longer needed.
System.debug('Accounts with contacts: ' + contactCountByAccount.size());Here the count map is much smaller than a Map<Id, List<Contact>> would be. If you only need counts, grouping full records is wasteful.
Choosing a strategy
The diagram shows the order in which to try the options when a transaction runs close to the heap limit.
Moving work to asynchronous Apex doubles the heap to 12 MB, but it is the last resort. For very large data volumes, Batch Apex resets the heap for each execute call, which is a better fit than a single Queueable job.
Common mistakes
- Querying inside a loop to avoid a big collection. This trades a heap problem for the 100-query limit. Query once, outside the loop.
- Testing only with small data. Code that passes with 20 records can fail at 20,000. Test with at least one bulk-sized data set (200 records for triggers is the standard chunk).
- Wrapping the work in
try/catchto handle heap errors.LimitExceptionis not catchable. CheckLimits.getHeapSize()againstLimits.getLimitHeapSize()before a risky step if you need a guard, and stop or defer work when usage is high. - Assuming the heap number is exact to the byte. The value is an approximation maintained by the platform. Leave a safety margin instead of aiming for 99%.
Boolean heapIsTight = Limits.getHeapSize() > Limits.getLimitHeapSize() * 0.8;
if (heapIsTight) {
System.debug('Heap above 80 percent; defer the remaining work.');
}Summary
Collections have no fixed element count, but they share a 6 MB (synchronous) or 12 MB (asynchronous) heap with everything else in the transaction. Reduce heap use by selecting fewer fields, filtering in SOQL, using SOQL for loops to process rows in batches of 200, and storing Ids or small values instead of full records. Measure with Limits.getHeapSize() and move to asynchronous Apex only when these steps are not enough.
Exercise
A trigger-called method runs List<Case> cases = [SELECT Id, Subject, Description, AccountId FROM Case]; and then builds Map<Id, Integer> countsByAccount by looping over cases. It fails with "Apex heap size too large" on large orgs. Name two changes that reduce heap use without changing the result, and say why catching the exception would not fix it.
Show answer
First, remove Subject and Description from the SELECT, because only AccountId is read, and long text fields take the most memory. Second, use a SOQL for loop (for (List<Case> batch : [SELECT AccountId FROM Case])) so only 200 records are in memory at a time, while the small countsByAccount map holds the result. Catching the exception would not help because System.LimitException for heap size cannot be caught, so the transaction still ends and rolls back.