Apex heap size too large
This 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)
This is a hard limit and cannot be increased any further.
Please check the best practices mentioned below to avoid the limit :
- We should not use class level variables to store a large amounts of data. All variables should be private, if not used by any other class.
- Use transient keyword so that the variable is not saved and it does not add up to the view state of the visual force page.
- Use SOQL For Loops to iterate and process data from large queries SOQL "for" loops differ from standard SOQL statements because of the method they use to retrieve sObjects.
- To avoid heap size limits, developers should always use a SOQL "for" loop to process query results that return many records. SOQL "for" loops retrieve all sObjects in a query and process multiple batches of records through the use of internal calls to query and queryMore.
example -
for (List<Contact> contacts : [select id, firstname, lastname
from contact where billingState = 'NY']) {
// implement your code to modify records in this batch
// commit this batch of 200 records
update contacts;
}
- Nullify the variables to make them out of scope as soon as they are no longer needed.
- Use 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 > 120000) {
// implement logic to reduce
}
So, work with SOQL queries and filtering them so that you can handle heap size error refering any of these -
Working with Very Large SOQL Queries - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_VLSQ.htm
Solutions to Fix Apex Heap Limits - https://www.eigenx.com/blog/2017/1/23/solutions-to-fix-apex-heap-limits
https://blog.jeffdouglas.com/2010/08/16/managing-the-heap-in-salesforce-com/
Apex Code Best Practices - https://developer.salesforce.com/page/Apex_Code_Best_Practices
Make SOQL query selective - https://help.salesforce.com/articleView?id=000325257&language=en_US&type=1&mode=1
Comments
Post a Comment