Some strategies on how to write Apex scripts that run within heap
limits.
1. Use soql for loop. This avoid heap size
as we are not storing the data in any variable but directly processing it in
the loop.
2. Store the required amount of data only. While
doing a query usually we retrieve all fields which increases the heap size. One
should only query those fields which they will work on. Reduce heap size
during runtime by removing items from the collection as you iterate over it.
3. Use local variables instead of class level
variable to store large amount of data. storing data in local
variable will go out of scope as soon as the method gets over. This helps in
cleaning heap size after use.
4. Use of Transient keyword to
declare instance variable that can not be saved, and shouldn't be transmitted
as part of the view state for the Visualforce page.
e.g: Transient Integer tempVar ; Some apex
objects are automatically considered transient, i.e their value does not get
saved as part of the page's view state. These objects are SavePoints, PageReference, XMLStream Classes,
etc. Static variables also don't get transmitted through the view
state.
5. Use Limit methods. Use heap limits
methods in your Apex code to monitor/manage the heap during execution.
Limits.getHeapSize() –
Returns the approximate amount of memory (in bytes) that has been used for the
heap in the current context.
Limits.getLimitHeapSize() –
Returns the total amount of memory (in bytes) that can be used for the heap in
the current context.
// check the heap size at runtime
if (Limits.getHeapSize > 275000) {
// implement logic to reduce
}
No comments:
Post a Comment