Understanding the Heap Size Error
The heap size error appears when you exceed the memory limit in a single transaction. Salesforce imposes a limit of 6MB for synchronous transactions and 12MB for asynchronous transactions. Heap size represents the total memory your code consumes during execution, including all variables, collections, and data structures.
Causes of the Heap Size Error
- SOQL queries returning too many records (typically more than 30,000) that get stored in memory
- Large collection objects (maps, lists, sets) holding excessive data
- Unnecessary temporary variables that accumulate and consume memory
- Inefficient code that reimplements functionality already available in Salesforce libraries
How to Handle the Heap Size Error
-
Optimize SOQL Queries: Add appropriate filter criteria to your SOQL queries to limit the number of records returned. Fewer records mean less memory usage. Consider adding WHERE conditions to return only 1-5 records at a time if possible.
-
Use Asynchronous Processing: For operations on large datasets, leverage asynchronous transactions like batch classes, future methods, or queueable apex, which have a higher heap limit (12MB).
-
Monitor Heap Usage: Use
Limits.getHeapSize()
to understand how much heap is being used at particular points in your code, andLimits.getLimitHeapSize()
to check the total available heap. -
Apply Coding Best Practices: Leverage built-in Salesforce Apex libraries instead of custom logic. For example, use the Math class for calculations and JSONGenerator for JSON structures. Minimize temporary variables, use short names for loop counters, and combine variable declarations where appropriate.