When triggers are build using “bulk design patterns” they
have better performance. The main advantage of bulkifying our apex trigger is it can handle a large
number of records efficiently.
While designing triggers we should always ensure that our
trigger should be able to handle multiple records at a time instead of
designing a trigger which handle a single record.
Now let see the difference between a trigger which handles a
single record and a trigger which handle bulk records.
The below trigger is designed to handle only one record it will
not work in case of bulk records. It will only handle the first record and the
other records are not handled.
trigger singleRecordTriggere on Account(before insert) {
Account obj = Trigger.New[0]; // Trigger
handling a single record
obj.industry = 'Agriculture';
}
The below trigger is designed to handle single or multiple
records at a time.
trigger singleRecordTriggere on Account(before insert) {
for(Account obj:trigger.new){ // Trigger handling bulk records or single record
obj.industry = 'Agriculture';
}
}
If we are dealing with SOQL queries, DML statements while we
are working with triggers we should always keep the below information in mind.
1) Avoid using SOQL queries inside for loop as shown below.
This is because we have a governor limit of 100 SOQL queries per an apex
transaction for synchronous apex and 200 SOQL queries per apex transaction for
asynchronous apex.
For(){
// SOQL QUERIES
}
Instead, we should use the “SOQL for loop” as shown in the below example.
For(Opportunity opp:[SELECT id,name from opportunity where
accounted in:accountIDSet]){
// Operations
}
2) While performing DML operations on record we should
always perform DML operations on a collection of records instead of performing on
each record individually. This is because we have the governor limit of 150 DML
calls in one apex transaction.
For example,
List<Account> updatedAccountList=new
List<Account>();
For(Account
obj:[ SELECT id,name from Account where id in: trigger.newMap.keySet()]){
obj.description=’Default
Description’;
updatedAccountList.add(obj);
}
If(updatedAccountList.size()
> 0){
Update
updatedAccountList;
}
No comments:
Post a Comment