Free computer code on screen

Addressing Apex Heap Size Issues

Salesforce enforces specific Apex Heap Size Limits, with a limit of 6MB for synchronous transactions and 12MB for asynchronous transactions. These limits are considered governor limits, meaning they are strict and cannot be adjusted.

The ‘Apex heap size too large’ error occurs when there is an excessive amount of data stored in memory during processing. The limit depends on the execution type (synchronous or asynchronous) and the current value.

To ensure your code operates within the Apex heap size limits, consider the following best practices:

  1. Avoid using class-level variables to store large data sets.
  2. Utilize SOQL For Loops to iterate and process data from extensive queries.
  3. Construct methods and loops in a way that allows variables to go out of scope when they are no longer needed.

For more details on these best practices, please refer to the following resource:

To resolve issues related to heap size errors, you should refactor your code according to these best practices to avoid exceeding these limits.

For additional information and strategies on managing heap size, you can visit the following links:

Here’s a troubleshooting approach to address heap size errors:

  1. Add the following debug method to the affected class:
void checkHeapSize(String tag) {
system.debug(tag + ': Heap size is ' + limits.getHeapSize() + ' enforced is ' + limits.getLimitHeapSize());

2a) Invoke the method at different locations within the code by passing a ‘tag’ parameter to identify where it’s called in the code. For instance, use ‘checkHeapSize(‘constructor1′);’.

2b) To monitor the heap limit, insert the check within a loop and perform the check every 1000th iteration. You can achieve this by introducing a local variable, such as ‘integer i;’, incrementing it for each iteration, and then executing the following code:

if (math.mod(i, 1000) == 0) } { call the method }.

3) Examine the debug logs to identify the heap size and check whether it exceeds the limit. When dealing with issues related to scheduled batches, it’s important to note that testing in the Developer Console will run code synchronously and display a limit of 6MB. However, the heap size limit for scheduled batches is the asynchronous limit of 12MB.

  1. If the heap size doesn’t exceed the limit, repeat steps 1-3. If the limit is exceeded, the debug logs should help identify the problematic section of code that requires correction.

Source: Credit: Sweta (Her profile is not available anymore – 404 error)