Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Thursday, May 29
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Apex»Handle Heap Size for Apex Code Optimization

    Handle Heap Size for Apex Code Optimization

    Dhanik Lal SahniBy Dhanik Lal SahniMarch 30, 2023Updated:January 15, 20254 Comments5 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Handle Apex heap size too large exception
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Heap size is the amount of memory needed to store the various objects, variables, and state of the Apex transaction in memory. This size is capped at 6MB for synchronous operations and is doubled to 12 MB for asynchronous processes. If the size is increased beyond this capped size then we receive the error “Apex heap size too large”. This post will list out ways to handle heap size for apex code optimization.

    To discuss this topic, let us see when we are getting heap size issues so that we can discuss a solution for the issue. As this issue is related to memory utilization while the transaction is in progress, this can be thrown when

    1. we are calling external API synchronously
    2. we are working on the file and using its content to write in a local variable for manipulation
    3. we have a lot of data stored in a global variable
    4. we are using loops and child loops to get details

    Apart from this, there can be other reasons also which are dependent on how we have written our apex code. Here is a sample code that will throw a Heap Size exception when order records will exceed 20000.

    Although the code has only SOQL and very simple list usage. A heap size error can be thrown as we are returning complete data from Order object and it is returning a lot of fields. Variable orders is storing complete data so when any calculation or processing will be done on this variable it can throw a heap size exception.

    Solution for all above mentioned issues is proper coding which follows best practices. We should write code that will use lesser memory in a transaction. Here are a few best practices that can reduce Heap Size exception

    1. Fetch only required records

    In the above example, we are returning the complete order list using SOQL which might not be required. Use some filter criteria so that only required records will be fetched. if we have fewer records then it will take lesser memory.

    We can use customerid as a filter criteria which will filter records and will reduce heap size. Check out our other post Use Filter in SOQL for the benefits of filtering records.

    2. Fetch only required fields

    In the above example, we have fetched so many fields but we are not using most of them in the code. All those fetched fields will take time to retrieve from the database and will hold memory as well when saved in any variable like orders in the above example.

    We should only fetch the required fields from the database. It will reduce the chances of heap size errors plus the code will work faster as well.

    3. Use for loop for SOQL

    In the above example, we have performed fetched data from the database and saved complete data in orders variable. This variable is used only in for loop and there is no other usage. We can avoid such type of SOQL and instead of this, we can directly use it in for loop.

    Another major benefit of using SOQL in for loop is it will be fetching only 200 records in one go and this way SOQL limit exceptions will not be thrown. So use this concept where ever you can apply it in apex code. I have removed all unused fields in the above example as well, this will also reduce memory size.

    4. Avoid system.debug

    Avoid the System.Debug in code. It can create issues in production. Checkout our other post for Optimize Code by Disabling Debug Mode

    5. Avoid class-level variables and use local variable

    Avoid class-level variables as they will be stored in memory until the complete transaction for that class is not finished. It will be better to use a local variable that will automatically release after that block execution.

    6. Instead of a big method use smaller methods

    As per best practice, we should create smaller methods around 20 lines. We should avoid bigger methods as they will create complexity and dependency in code. A variable created in the method will be alive till the method execution so if we have smaller methods then the variable will be cleaned early just after method execution so our heap size will have more space to hold other objects.

    In the case of a bigger method, the variable will be in the heap until the complete method is not executed, it will take some space and might be a reason for the heap size exception. So better will create smaller methods.

    7. Free memory when not in use

    Where ever we are using objects to store data, try to remove them from memory immediately after use. We should not leave everything for the system to clean. Make a practice to clean it immediately and free some memory from the heap. This will help in storing other data for functionality. In the above example, we have an orders variable that can be cleaned after for loop. Assign null to clean object memory.

    8. Use Asynchronous Methods

    Sometimes we need to do some heavy operations and it might need to use too much memory, in that case, we can use asynchronous methods so that the heap size will be increased to 12MB and we can complete our apex transaction. We can use Future callouts, queueable methods, or batch jobs based on the requirement. We can use this approach for callout, file handling, etc.

    References

    Optimizing Loop in Apex Code

    Error ‘Apex heap size too large’

    What is the main reason for Heap size limit error?

    Build Scalable Solutions with Salesforce
    Avoid Batch Apex and Use Queueable Class

    Queueable Vs Batch Apex In Salesforce

    Other related posts

    Optimizing Salesforce Apex Code

    DML or SOQL Inside Loops

    Limiting data rows for lists

    Stop Describing every time and use Caching of the described object

    Use Filter in SOQL

    Optimize Trigger

    Bulkify Code

    Foreign Key Relationship in SOQL

    apex apex heap exception apex heap size issue Apex heap size too large Asynchronous apex asynchronous processes in salesforce batch apex future method handle apex heap issue Queueable salesforce salesforce apex
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleShopify integration with Salesforce using Webhook
    Next Article Book Testimonials – Salesforce for Beginners
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni4 Mins Read

    How to Build a Generic Modal Window in Lightning Web Component

    May 26, 2025
    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    View 4 Comments

    4 Comments

    1. Pingback: Ultimate Checklist for Efficiently Querying Large Data Sets

    2. Pingback: Integrate Google reCaptcha v3 into the Salesforce Sites

    3. Pingback: Optimizing Salesforce Apex Code | SalesforceCodex

    4. Pingback: How to Manage Technical Debt in Salesforce | SalesforceCodex

    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) file upload (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (30) Lightning web component (62) lwc (51) named credential (8) news (4) optimize apex code (4) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (141) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) file upload (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (30) Lightning web component (62) lwc (51) named credential (8) news (4) optimize apex code (4) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (141) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.