2

I have the following scenario occuring in my code:

Custom Object A has 100 records.

Custom Object B also has 100 records (every record of B will have a corresponding record with A).

for (Custom_Object_A a : A_Collection) {
    for (Custom_Object_B b : B_Collection) {
        if (b.id == a.id) {
            b.field1 = a.field1;
        }
    }
}
update B_Collection;

So the above code will execute 100 * 100 = 10000 computations.

Will this be memory intensive on Salesforce ?

7

Just use a map. By the way, two records of different SObjectType will never have the same Id, because they will have a different key prefix (the first three characters). You can see this for yourself:

system.assertNotEquals(SObjectType.A__c.getKeyPrefix(), SObjectType.B__c.getKeyPrefix());

I will assume there is some sort of lookup relationship. It does not really matter which direction. I will take your word that the relationship is 1-to-1.

Map<Id, A__c> aMap = new Map<Id, A__c>([SELECT Id FROM A__c]);
for (B__c b : [SELECT A__c FROM B__c])
    A__c correspondingRecord = aMap.get(b.A__c);
|improve this answer|||||
  • Hmm...I was doing Map before. also..i just wanted to which one would be less strainful on Salesforce servers..I am gonna keep the processing with the @future notation as such i will have like 60 sec of CPU time when compared to synchronous which is 10 sec... – Rainmaker Mar 10 '16 at 3:25
  • Um. So does this answer your question? I'm not sure I follow. – Adrian Larson Mar 10 '16 at 3:26
  • Tx for your response....I did try out the functionality via Map and its working fine. I just wanted to know which among these two ("M x N" vs Map) is less strainful on Salesforce servers ?..Hope I am clear – Rainmaker Mar 10 '16 at 3:30
  • It is definitely more efficient to use a map and a single loop. Apex generates Map<Id, SObject> very efficiently. – Adrian Larson Mar 10 '16 at 3:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.