Loading

Build better apex scripts to manage heap limits

Дата публикации: Jun 14, 2026
Описание

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.

Решение

Strategy 1: Monitor Heap Size in Debug Logs

Review debug logs for heap size information. If heap size is approaching the limit, investigate the code and refactor to reduce memory usage.

Strategy 2: Use the Transient Keyword

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.

Strategy 3: Use Limit Methods to Monitor Heap at Runtime

Use the following Limits methods in your Apex code to monitor and manage heap size during execution:

  • Limits.getHeapSize() — Returns the approximate amount of memory (in bytes) currently used for the heap in the current context.
  • Limits.getLimitHeapSize() — Returns the total amount of memory (in bytes) available for the heap in the current context.

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
}

 

Strategy 4: Remove Items from Collections While Iterating

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.

Strategy 5: Use SOQL For Loops

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

 
Загрузка
Salesforce Help | Article