function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Test Q 13Test Q 13 

Heap size too large while extracting records in CSV Format and sending an Email to the User

I want to send an Email to User with CSV attached for all the records present in a Report subscribed by him.
SwethaSwetha (Salesforce Developers) 
Salesforce enforces an Apex Heap Size Limit of 6MB for synchronous transactions and 12MB for asynchronous transactions.

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)

Strategies on how to write Apex scripts that run within heap limits :
========

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 methods. 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 > 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.

How to avoid the Apex heap limit error :
======
https://help.salesforce.com/articleView?id=000321537&language=en_US&type=1&mode=1

I would also like to share few other related articles with you :
========
http://blog.jeffdouglas.com/2010/08/16/managing-the-heap-in-salesforce-com/
http://salesforce.stackexchange.com/questions/50362/heap-size-limit-in-salesforce
 
Hope this helps you. Please mark this answer as best so that others facing the
same issue will find this
information useful.
 
Thank you