What To Do When Salesforce Apex Heap Size Increases?

Welcome to Salesforce! You've just encountered your first governor limit emoji1.

The 'Apex heap size too large' error occurs when too much data is being stored in memory during processing.Total heap size must be <= 6 MB.

h

What you can do to Overcome it :

1.) Don't use class-level variables to store a large amount of data. Only those variables which are used on the Visualforce page should be public rest all variables should be private, if not used by any other class.

2.) Utilize SOQL For Loops to iterate and process data from large queries. Best way to write a query in for loop to avoid filling space of heap by creating a list like :

Map accountMap = new Map();
for(Account tempAcc : [Select Id, Name From Account Limit 10000]){
    accountMap.put(tempAcc.Id , tempAcc.Name);
}

3.) Nullify the variables to make them out of scope as soon as they are no longer needed.

//Fetching account records
List accLst = [Select Id, Name From Account Limit 10000];
Map accountMap = new Map();
for(Account tempAcc : accLst){
    accountMap.put(tempAcc.Id , tempAcc.Name);
}
//To reduce heap size accLst = null;

4.) Use of Transient keyword to declare instance variable that can not be saved, and shouldn't be transmitted as part of the view state for the Visualforce page. e.g: Transient Integer tempVar ; Some apex objects are automatically considered transient, i.e their value does not get saved as part of the page's view state. These objects are SavePoints, PageReference, XMLStream Classes, etc. Static variables also don't get transmitted through the view state.

"It's not about where you were born. Or what powers you have. Or what you wear on your chest. It's about what you do...action."

Popular Salesforce Blogs