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.


What you can do to Overcome it :

1.) Don’t use class level variables to store a large amounts of data.Only those variables which are used on visual force 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 query in for loop to avoid filling space of heap by creating a list like :


Map accountMap = new Map() ;</p><p>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 visual force page.e.g : Transient Integer tempVar ;Some apex objects are automatically considered transient, i.e thier value does not get saved as part of page’s view state. These objects are SavePoints , PageReference, XMLStream Classes etc. Static variables also don’t get transmitted thorugh 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.”

Article Resource: https://salesforce.stackexchange.com/questions/143598/%20exceeded-max-size-limit-of-6000000


Leave a Reply


We're not around right now. But you can send us an email and we'll get back to you, asap.


About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2020 Forcetalks. All Right Reserved.

Log in with your credentials


Forgot your details?