[SalesForce] Best practice using Schema.SObjectType

Wants to know please,

1) Why using the Schema.SObjectType is better than using a SOQL?

2) If using the Schema.SObjectType inside a for loop is a bad Idea…
for example:

Id devRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Development').getRecordTypeId();

I checked and saw that this doesn't affect the SOQL governor Limit – So I guess this is ok to use it inside a for loop?

Best Answer

Calling Schema class again and again in loop is not a best practice. It doesn't consume soul limits but can cause

cpu time limit exceed exception

. So what I normally do is get schema describe result of any object outside loop and then inside loop get which ever value you want to get from that object.

Like for your case I will do

Map<String, Schema.RecordTypeInfo> recordtypeMap = Schema.SObjectType.Account.getRecordTypeInfosByName();

and in loop use recordtypeMap.get('recordtype').getRecordTypeId();

In this way I am calling schema class only once and using it at multiple places.

Related Topic