If you have been in Salesforce’s Apex world for a while, you would have heard the words “Bulkify Your Code”. There are an abundance of reasons why you shouldn’t simply ignore these words and I’m going to let you into the some secrets as to why.
If you are, like me, a fan of writing Salesforce triggers, this will help you no end. However, I’d suggest taking some time to fully understand them. In this blog, I will cover the reason why bulkifying your Apex code in a Salesforce trigger is important and give you a working example to help you understand the process.
What does Bulkifying Apex Code mean?
In simple terms, bulkifying your Apex code refers to its ability to properly handle multiple records at one time.
Displayed in the screen shot below is a trigger that is fired of an update to Accounts’ custom field “test__C” which updates the custom field “dependant_test__C” with the same value that has been set to “test__C”.
As you can see, the decision to update the Account as well as the update statement is within a for loop. In plain English, for each Account that has been updated, decide if we need to update the custom field in question and if so, perform the update.
I have bulkified this trigger and this is the result:
As you can see, I have created a list of Accounts before the for loop and have moved the update statement outside of the for loop. The only thing that is being done now inside the for loop is the decision to update the account – if the account needs to be updated; we add it to the new list.
Why should I bulkify my code?
As mentioned above, there are a number of reasons to bukify your code. I will cover one reason to bulkify your Apex code in a Salesforce trigger: data imports.
My trigger, displayed in the first screen shot, works just fine if one or even two Accounts have been updated. But what if a thousand Accounts are updated using Bulk Api (used by tools like Data Loader)? A single instance of the Apex code, which is our trigger, is executed; meaning we will try to make a connection to the database and update a single account a thousand times within a matter of seconds. The Apex code will most likely die and if it does not, it’s still bad.
In the second trigger, the for loop loops through a thousand Accounts, only makes a decision and adds records to a list. The Updates are then executed in one go which significantly reduces the load on the database thus ensuring our Apex code is executed successfully.
This is one of the many reasons why bulkifying your code wherever you can is so important. I strongly advice anyone working with Apex to take some time and learn this concept.
For more information on this topic, please refer to the link below: