Sub topic 16
Heap size and collection limits
This chapter assumes you can write Apex Lists, Sets, and Maps, load them from SOQL, and group records with a Map of Lists. It covers how much memory those collections can use in one transaction and what to do when they use too much.
What the heap is
The heap is the memory your code uses while a transaction runs. Every collection, every record in it, and every string it holds counts toward the heap. Apex does not limit how many elements a collection can hold. The heap limit is what stops you.
| Execution context | Heap limit |
|---|---|
| Synchronous (triggers, controllers, anonymous Apex) | 6 MB |
| Asynchronous (Batch, Queueable, Future) | 12 MB |
If you go over, Apex throws System.LimitException: Apex heap size too large. You cannot catch this exception, so the transaction ends and rolls back.
Measuring heap use
The Limits class reports current use. Check it before and after a step you suspect is expensive.
System.debug('Start: ' + Limits.getHeapSize() + ' of ' + Limits.getLimitHeapSize());
List<Account> accounts = [SELECT Id, Name, Description FROM Account LIMIT 10000];
System.debug('After query: ' + Limits.getHeapSize());
accounts.clear();
accounts = null;
System.debug('After release: ' + Limits.getHeapSize());Heap size is an estimate, and it only drops after Apex reclaims memory. Use the numbers to compare steps, not as exact byte counts.
Which collections get large
Collections of SObjects grow fastest, because each record carries every field you queried. Three things make this worse:
- Querying fields you never read, especially long text fields.
- Building several collections from the same data, such as a
List, aMapkeyed by Id, and aMapof Lists. - Cloning.
clone()anddeepClone()create new objects, so they add to the heap. Copying a reference does not.
Reducing heap use
- Select only the fields you need.
- Store Ids instead of whole records when an Id is enough. A
Set<Id>is much smaller than aList<Account>. - Use a SOQL for loop for large result sets.
- Clear large collections or set them to
nullonce you are done with them. - Move heavy work to Batch Apex, which has the 12 MB limit and handles the data in chunks.
A SOQL for loop fetches records in batches of 200 instead of loading the whole result into a list.
Set<Id> accountIds = new Set<Id>();
for (Account a : [SELECT Id FROM Account WHERE Industry = 'Energy']) {
accountIds.add(a.Id);
}
System.debug(accountIds.size());The loop variable holds one batch at a time, so only the Set<Id> keeps growing. Compare that with assigning the query to a List<Account>, which holds every record at once.
Limits that apply alongside the heap
The heap is not the only limit that affects collections. These per-transaction limits cap what you can load and save.
| Limit | Synchronous value |
|---|---|
| Total records returned by SOQL | 50,000 |
| SOQL queries | 100 |
| Records processed by DML | 10,000 |
| DML statements | 150 |
How the limits fit together
Exercise
A trigger loads 40,000 Contacts into a List<Contact> with every field selected, then fails with "Apex heap size too large". Name two changes that reduce heap use without changing what the code does.
Show answer
Select only the fields the code reads, and process the records with a SOQL for loop instead of holding the whole list. If the code only needs Ids, collect them in a Set<Id>. Setting the list to null after use also helps.