Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • 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
    • Enhancing Performance with File Compression in Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Tuesday, May 20
    • 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»Optimize Apex Code by Metadata Caching

    Optimize Apex Code by Metadata Caching

    Dhanik Lal SahniBy Dhanik Lal SahniJanuary 20, 2022Updated:January 20, 20226 Comments5 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Optimize Apex Code by Metadata Caching
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Most of the time we need metadata of entities and fields to make dynamic pages especially in the project that is being developed for the App Exchange marketplace. Schema class has two methods Schema.getGlobalDescribe() and Schema.describeSObjects() which are used to get metadata information. If we call these methods multiple times or in the loop, it will affect application performance. This post will give detail on how to optimize apex code by metadata caching.

    Let us see both methods one by one.

    1. Schema.getGlobalDescribe

    Schema.getGlobalDescribe will return a huge list of all custom and standard objects, custom metadata definition, external objects, custom setting, and big objects. This list will vary based on org to org. If any org has so many objects then it will take a longer time to describe using this method. This method will create a complete map of all objects and if called multiple times, it will increase CPU time which will affect performance.

    Take an example, the developer needs to get all custom settings of a client Org when the setting page is loaded. So he/she can use getGlobalDescribe method to get a list of call custom settings from client Org.

    In the above code, we are getting all details using Schema.getGlobalDescribe.

    Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

    Schema.getGlobalDescribe is a heavy process and if we are calling this method multiple times, it is a big problem for application. So what are possible ways to handle this properly?

    1. Use static property
    2. Use Caching mechanism to store the output

    Let us see both approaches one by one to make better code.

    i. Use Static property

    We can create a static property that will call Schema.getGlobalDescribe(); only once when the first time method is called. As it is a static property, it will be called only once in one transaction. This will be useful when we are calling describing method in loops.

    static Map<String, Schema.SObjectType> globalDescribe=null;
    public static Map<String, SObjectType> globalDescribe {
        get { if(globalDescribe == null) globalDescribe = Schema.getGlobalDescribe();
            return globalDescribe;
        }
    }

    ii. Use Caching mechanism to store the output

    The above solution will work in the case of one transaction, what if we need it in another transaction or needed by another user. For this, we have to store the output in cache location. We can use Session or Org cache. We should go with the Org cache as this will be helpful for other users as well. So now the above implementation will be updated like the below code. I have created one platform cache (schema) to test this implementation.

    When this code is executed first time, it will get metadata from the global describe call. When getCustomSetting() is called the second time it will get the result from the cache. Right now we have just cached the result of Schema.getGlobalDescribe(). If we need to cache query string (after line#37), that also can be cached. This will be dependent on the use case and individual requirements.

    If org has very few custom objects then this will not give improvement to performance. Might be it will decrease performance as well as putting/retrieving data from the Platform Cache will take time also.

    Testing above approaches:

    Test the above code using the below code line. You can check the time taken for global describe. This code can be executed multiple times to see CPU time is being saved or not.

    When I have tested DescribeService.getCustomSetting() in one of the org where around 6 custom settings were there. Here is the time taken by code when multiple time methods are called. Again this can be dependent on the number of custom settings as well in your org.

    Apex CPU time comparision

    2. Schema.describeSObjects

    We should only call Schema.getGlobalDescribe() when you are not aware of the object but if you know the object name or you have very few objects to describe, We can use Schema.describeSObjects method for the metadata describes.

    Schema.describeSObjects will return metadata (field list and object properties) for the specified sObject or array of sObjects. This can also create a performance issue if we call this multiple times or in the loop. We should cache result of object describe for later use.

    When we don’t know the object name in advance and we need to describe a few objects then below is a better approach. We can use Type newInstance method to get metadata.

    Metadata information should be stored in the cache for later use.

    Summary:

    1. Methods Schema.getGlobalDescribe() or Schema.describeSObjects should be called once per an apex transaction
    2. Methods Schema.getGlobalDescribe() or Schema.describeSObjects should never be called inside a loop or repeatedly.
    3. If we need the describe information for every object in the organization, the method Schema.getGlobalDescribe() should be used and its results should be cached.
    4. If we need the describe information for known many objects, the method Schema.describeSObjects() should be used with a parameter of the list of object names. The result should be cached and reused instead of the calling method again.
    5. If we need to describe information for a few unknown objects then we can use the Type instance approach.

    Old posts related to Performance Optimization

    Optimizing Salesforce Apex Code

    Optimizing Loop in Apex Code

    Optimize Code by Disabling Debug Mode

    References:

    https://salesforce.stackexchange.com/questions/218982/why-is-schema-describesobjectstypes-slower-than-schema-getglobaldescribe

    https://salesforce.stackexchange.com/questions/262146/how-to-improve-schema-access-performance?noredirect=1&lq=1

    apex code optimization optimize apex optimize apex code optimize code platform cache Schema.describeSObjects Schema.getGlobalDescribe
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleOptimize Code by Disabling Debug Mode
    Next Article Optimize SOQL Filter in Apex Code
    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 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
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Dynamic Queueable Chaining in Salesforce Apex

    April 21, 2025
    View 6 Comments

    6 Comments

    1. Kishan on January 31, 2022 3:42 pm

      excellent post.

      Reply
      • Dhanik Lal Sahni on February 3, 2022 7:49 am

        Thank You Kishan.

        Reply
    2. Pingback: What are Salesforce Big Objects? - SalesforceCodex

    3. Pingback: Salesforce Architect Interview Questions - Salesforce Codex

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

    5. Pingback: Optimizing Salesforce Apex Code | SalesforceCodex

    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • 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
    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 (110) 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) einstein (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 (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex (3) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (140) 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
    • 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
    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 (110) 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) einstein (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 (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex (3) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (140) 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.