Print this page

Some strategies on how to write Apex scripts that run within heap limits.

Knowledge Article Number 000170956
Description Some strategies on how to write Apex scripts that run within heap limits.
Resolution 1.  Look for heap size in debug logs. If heap size is approaching the limit, investigate it and refactor the code.

2. Use the 'Transient' keyword with variables. It is used to declare instance variables that cannot be saved, and shouldn’t be transmitted as part of the view state for a Visualforce page.

3. Use Limit methodsUse heap limits methods in your Apex code to monitor/manage the heap during execution.
  • Limits.getHeapSize() – Returns the approximate amount of memory (in bytes) that has been used for the heap in the current context.
  • Limits.getLimitHeapSize() – Returns the total amount of memory (in bytes) that can be used for the heap in the current context.

// check the heap size at runtime
if (Limits.getHeapSize > 275000) {
     // implement logic to reduce
}

4. Reduce heap size during runtime by removing items from the collection as you iterate over it.

5. Use SOQL for loops. To avoid heap size limits, developers should always use a SOQL "for" loop to process query results that return many records. See http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_loops_for_SOQL.htm for more information.
 





promote demote