function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nag22Nag22 

Is this trigger Bulkified?

HI....

 

There are 2 objects one ObjA and ObjB  . On objA there is a TEXT field  and these values are refer to ObjB NAME field.

Now I want to copy the id of ObjB into ObjA as lookup.. for  that I have written a trigger

Is this trigger bulkified or not?

If not any suggestions to improve my code for bulkification?

 

trigger PriceTrig on Ales__c (before insert,before update) {

 list<String> Str= new list<String>();
  
  for(Ales__c S:trigger.new){
    Str.add(S.Prod__c);
  }


 list<SProducts__c> Prod= [select id,name from SProducts__c where name in: Str limit 1000];
   
    for(Ales__c SNEW:trigger.new){
     
       for(SProducts__c SP:Prod){
       
           if(SNEW.prod__c == SP.name){
            
                SNEW.SProductid__c = SP.id;        
           }
       }
    }
        
}

 

 

Vinit_KumarVinit_Kumar

Hi,

 

This trigger looks good to me and looks bulkified too.

kiranmutturukiranmutturu

yes,

kibitzerkibitzer

Hi…

 

This will work but it’s not great.

 

Take a worst case where you are updating 200 objects at once. You may have up to 200 entries in the Str list, which could pull up to 200 objects from the SProducts list.

Your loop to do the assignment runs 200 x an average of 100 or 20000 operations. With a conditional and assignment you’re looking at maybe 40,000 script lines – which is well under the 200,000 limit – so it will work. But it’s not great.

 

Here’s how to change it.

 

  1. It’s always better to move code out of the trigger and into a class – best practice.
  2. Use a set instead of a list for Str. If you have more than one object with the same Prod__c field, this will reduce memory use and make the query more efficient.
  3. After the query, build a map of SProducts__c keyed to the name – something like this:
Map<String, SProducts__c> prodmap = new Map<Stirng, SProducts__c>

for(SProducts__c SP:Prod) prodmap.put(SP.name, SP);

 

 

Now change your loop to use the map:

 

for(Ales__c SNEW:trigger.new){
     
      
           if(prodnamp.containskey(SNEW.prod__c)){
            
                SNEW.SProductid__c = prod.get(SNEW.prod__c).id;        
           }
       }
    }

 

Worst case script count is now about 200 for the first loop, 200 to build the map, and maybe 600 for the final loop.

Obviously, I haven’t tested this – so can’t guarantee the syntax – but the approach is sound.