The accepted answer (and the other existing alternative) relies on the use of Schema.getGlobalDescribe()
. While this is quick, easy and obvious to code, it comes at a performance cost.
The first access to this from your org in a while (the describes get cached by Salesforce for a time it seems, or at least some of the underlying metadata does) this can cost over 700ms to return the map - timing testing on a scratch org using Datetime.now().getTime()
before and after - only dropping to between 100 and 300ms thereafter on the same org. If you consider you have a maximum of 10 seconds CPU time for a given transaction against the server, this is a real waste. (It must be said, the Limits.getCpuTime
method doesn't count the entire cost here, but it is still over 100ms from my testing.)
On the other hand, the following method takes between 2 and 15ms (and averaging around 5ms) to execute, giving the same result:
String typeName = ...; // E.g. 'Case' or 'Account' etc.
SObject instance = (SObject) Type.forName('Schema.' + typeName).newInstance();
String idPrefix = instance.getSObjectType().getDescribe().getKeyPrefix();
Getting the Type
for a given typeName is fast and efficient. The modest overhead of creating an empty SObject
from the Type
has little impact on heap or CPU, and getting the describe for the instance is very fast.
Clearly, if your code needs many different ID prefixes in one transaction (e.g. more than 10-15 different objects' prefixes) it can become more efficient to use the global describes.
UPDATE:
If you go to the trouble of using the updated Schema.describeSObjects
, ensuring that the SObjectDescribeOptions.DEFERRED
option is applied, you can get even better performance. For example:
String typeName = ...;
List<Schema.DescribeSObjectResult> describes = Schema.describeSObjects(new String[] { typeName }, SObjectDescribeOptions.DEFERRED);
String idPrefix = describes[0].getKeyPrefix();
This, surprisingly, has better performance compared with the use of Type.forName
. With my testing (on the same scratch org) I got real time timing of between 2 and 8 milliseconds (the latter actually not on first use of the org for a while, which was 5ms), and a CPU limit timing of between 1 and 3 milliseconds. This makes it the fastest and most repeatable way to access the schema to get the ID key prefix.