Best practices for running within the Apex heap size
Salesforce Advice
Reduce class level variables data storage
Don't use class level variables to store a large amounts of data.
User SOQL for
Loops
Utilize SOQL For Loops to iterate and process data from large queries.
for(Conatct ctt : [Select Id,Name,Account.Name FROM Contact]) {
// do your work
}
Shorten variables lifetime
Construct methods and loops that allow variables to go out of scope as soon as they are no longer needed.
Other Advice
Using Efficient Algorithms
Being the heart of any code, algorithms can make or break the running of your application. A good space-efficient algorithm can save a lot of your heap memory while simultaneously performing smoothly. Before developing any logic or writing any code snippet, sit, and think through the algorithms to use and choose the one that serves your purpose and makes use of the heap memory efficiently. Try not to split the parts of your algorithms into different functions; rather try to keep them in line when used only within that code.
Built-in Apex libraries
Try to leverage and make use of the inbuilt Apex libraries that Salesforce provides other than writing your custom logic for everything. For example, use the Math class for performing mathematical operations, use JSONGenerator class to create JSON structures, and many more. One line of method calling code is way better than rewriting the logic on your own. This not only saves you time but also the heap memory is managed efficiently.
Avoid using temporary variables
Creating temporary variables is a favorite practice of many developers. We unknowingly create such variables in our code without realizing that we can do without them. These variables take up unnecessary space and add up to the heap memory.
Shorten variable names & declarations
You can spare characters when naming temporary variables like loop counter variables as i instead of myCounter. You should keep meaningful names according to the business.
You can also combine variable declarations like:
Integer i = 0, j = 10;
Shorten Field API Name
We all love to give meaningful names to the custom fields in Salesforce objects. Little do we know that a long API name impacts the code heap size. For example, it is counted in SOQL query size, code that references the field, and each time it is accessed. Maximum length of SOQL statements is 100K.
Remove unnecessary debug statements
Since all the debug statements are counted against the code length, it is necessary to keep a cap on them in order to limit the consumed heap size of the Apex code. It is fine to use them while doing the apex development but should be removed or minimized in the final production version of the code.
Reference
- SOQL For Loops
- Error 'Apex heap size too large'
- Heap Size: Elephant in the room
评论已关闭