Print this page

Best Practices to avoid Apex Heap size too large error

Knowledge Article Number 000004186

The "Apex heap size too large" error occurs when too much data is being stored in memory during processing. The limit depends on the type of execution (E.g. synchronous vs asynchronous calls) and current value can be found in the Apex Developer's Guide.






Best practices for running within the Apex heap size


  • Don't use class level variables to store a large amounts of data.
  • Utilize SOQL For Loops to iterate and process data from large queries.
  • Construct methods and loops that allow variables to go out of scope as soon as they are no longer needed.

In the below sample, while we could be processing 50000 items, the largest heap would contain a search term, a query, a list of 200 accounts, and a list of the results. This is relatively small in the scope of everything that's being processed.

public with sharing class myClass{

private String myString;

    public myClass(String searchString) {
        myString = searchString;

    private string getQueryString() {
        return 'SELECT Id, Name FROM Account LIMIT 50000';

    public List<Account> getSearchResults() {
        List<Account> searchResults = new List<Account>();
        for(List<Account> accts : Database.Query(getQueryString())) {
            // Each loop processes 200 items
            for(Account a : accts) {
                if (a.Name != null && a.Name.contains(myString)) {
        return searchResults;


Want to learn more on this topic? Review our documentation regarding SOQL For Loops.

promote demote