Reducing heap size usage
The heap size is the amount of memory being used to store the various objects, variables, and state of the Apex transaction in memory as it is being processed. For synchronous operations, this is capped at 6 MB and is doubled to 12 MB for asynchronous processes.
Put simply, the way to improve usage of the heap size is to hold less information in memory. Heap size is an interesting governor limit as it has little impact on visible performance to the end user. The end user will never be aware of some code taking 1 MB or 5 MB of heap up, unlike CPU time, where they will perceive the delay in responsiveness. Should you be working with larger datasets, the heap size can start to grow and a number of actions can be taken to reduce it. For the first of these, let's return to for
loops.
Batched for loops
When discussing for
loops in the preceding examples, we noted how storing the records we wish to iterate through in a variable to improve CPU time leads...