1.6 Initial understanding of governor limit and bulkification

The concept

Let’s first try to execute the following code first.


for(Integer i = 0; i < 200; i++)
{
    Merchandise__c mer = new Merchandise__c();
    mer.Name = 'Sample test good ' + i;
    mer.Original_Price__c = 100;
    
    insert mer;
}

Execute this code and you are supposed to get the following error:

toomanydml

What is that error about?

This error is about a most important concept in Apex programming, if not the most important concept – governor limit and bulkification.

In short, you can’t do too many DML operations in one execution. Currently the limit is 150. Salesforce forced you to reduce the number to be no greater than that.

Why is that? You may wonder? Because Salesforce is a cloud environment, which means we are sharing the CPU, memory and other resources with our neighbours on the internet. If we are occupying all the resources, then we will be bad neighbours.

Consider the above statement, we are trying to execute DML statements 200 times, which means 200 database operations. It will be a lot of calling, locking and resources. It is not a good practice even in the normal scenario. And it is extremely bad in a shared environment.

So, that is governor limit. What is bulkification? In short, bulkification is to minimise the usage of DML and SOQL calls and any other statements which has a certain governor limit. We will talk about SOQL in next chapter. In short, you should never put DML or SOQL statements inside a loop.

So, how should we optimise our code?

In the above code, we should put all the data we want to insert into database into a list, and then perform DML upon the list. It will be only one DML statements then.


List<Merchandise__c> merToInsert = new List<Merchandise__c>();
for(Integer i = 0; i < 200; i++)
{
    Merchandise__c mer = new Merchandise__c();
    mer.Name = 'Sample test good ' + i;
    mer.Original_Price__c = 100;
    
    merToInsert.add(mer);
}

insert merToInsert;

Execute this code. You will notice it executes much faster than the previous one, too.

A bit explanation

This is the first example of bulkification. Your actual scenario of bulkification could be more complicated. But it should give you a brief idea about what is governor limit and bulkification and what should be avoided. We will talk more about how to do bulkification under difference circumstance in Chapter 5.

Next Post

2.1 Use SOQL and where statement to retrieve data

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *