+ Start a Discussion
Charles KopplemanCharles Koppleman 

Why is querying FieldDefinition from CustomMetadata so slow?

When I query string columns on custom metadata objects, I get decent performance.  However, if I query a column that points to a FieldDefinition, my query became much slower.

Is this a known system bug?  Is there a patch on the horizon?

It makes these relationships really unusable.

Here are profiling logs on a sandbox after priming the pump (I'll just include the SOQL profiling):

Querying a String takes 19ms.

    for (My_Metadata__mdt m: [SELECT Id, String__c FROM My_Metadata__mdt]) {
        System.debug(m.id);
    }

    AnonymousBlock: line 1, column 1: [SELECT Id, String__c FROM My_Metadata__mdt]: executed 273 times in 19 ms

Query a FieldDefinition takes about half a second!

    for (My_Metadata__mdt m: [SELECT Id, Field__c FROM My_Metadata__mdt]) {
        System.debug(m.id);
    }

    AnonymousBlock: line 1, column 1: [SELECT Id, Field__c FROM My_Metadata__mdt]: executed 273 times in 511 ms
Phil WPhil W
@Charles Koppleman, I believe this is because this mechanism uses "dynamic schema access" to load the schema describes and this is a very inefficient mechanism. We spent a while profiling various scenarios for schema access and discovered that there are two separate per-session cache for the data depending on how you access it (static or dynamic) and that dynamic access is always really slow. Salesforce really needs to re-work the internals of this custom metadata type schema access handling to use the static approach. Take a look at my posting on Stack Exchange (https://salesforce.stackexchange.com/questions/262146/how-to-improve-schema-access-performance/262147#262147) for some discussion on this.