Sometimes you need to access the same data multiple times during a transaction. Instead of re-querying the data it can be cached. This way you can save on the SOQL queries
I have seen in many orgs during my years that same data is queried over and over again during the transaction. This consumes a lot of unnecessary SOQL queries.
A simple and yet effective way of caching SOQL results is to define a static variable that will keep the result stored in memory for the duration of the transaction
Just check if the static variable is null and if not then return result
Here is an example implementation using a getter
public static List<Account> listOfAccounts {
get {
if(listOfAccounts == null) {
listOfAccounts = [SELECT Id, Name FROM Account LIMIT 100];
}
return listOfAccounts;
}
set;
}

Leave a comment