Apex heap size limits define the maximum amount of memory that can be allocated during a single Apex transaction. In synchronous Apex transactions, the heap size limit is 6 MB. In asynchronous transactions (Batch Apex, Queueable Apex, and Future methods), the limit is 12 MB. Exceeding the heap limit throws a System.LimitException: Apex heap size too large error, which aborts the transaction. This article describes five strategies to reduce heap usage and keep Apex code within governor limits.
Review debug logs for heap size information. If heap size is approaching the limit, investigate the code and refactor to reduce memory usage.
Use the Transient keyword with instance variables that do not need to be saved or transmitted as part of the view state for a Visualforce page. Transient variables are excluded from the heap size calculation for view state purposes.
Use the following Limits methods in your Apex code to monitor and manage heap size during execution:
The following Apex pattern checks heap usage at runtime and can trigger logic to reduce memory before the governor limit is reached:
// check the heap size at runtime
if (Limits.getHeapSize > 275000) {
// implement logic to reduce
}
Reduce heap size during runtime by removing items from a collection as you iterate over it. This frees up memory progressively rather than holding all records in memory simultaneously.
To avoid heap size limits when processing large query results, use SOQL "for" loops instead of querying all records into a List variable. SOQL for loops process records in batches, keeping heap usage low.
000385712

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.