Avoid hitting governor limits


DML operation
Using DML statement inside the for loop is not a good practise.Total number of DML operation can be performed in a Apex class is 150. The following example doesn't bulkify DML operation, it will throw an Apex governor limit exception.

In this example for loop iterates over LineItem contained in the liList list variable, for each iteration it will update Line item with new description. It will work up to 150 recrds, for the 151st records this trigger throws an run time exception for exceeding governor limit for DML operation.



So how can we over come this issue? one straight answer is avoid DML operation inside the for loop
Below example is recommended alternative code which will work in Bulk operation

More efficient SOQL Queries
Similar to DML operation placing the SOQL query inside the loop is not a good practise. Total number of SOQL query issued in the apex class is 100. The following example
shows the inefficient querieng of child item.

The SOQL query performed inside the loop retrieves the Line item for each invoice statement.
When updating more than 100 Invoice statement records, it will throw the run time exception for exceeding governor limit for SOQL queries.



Below is the recommended alternative code for SOQL query.This example bypasses the problem of having the SOQL query called for each item. It has a modified SOQL query that
retrieves all invoice statements that are part of Trigger.new and also gets their line items through the nested query. In this way, only one SOQL query is performed and we’re still within our limits


SOQL For Loop
Use SOQL for loop to operate on records in batches of 200, it helps to avoid heap size limit of 6 MB

Query without For Loop
The following example of query will return all the Account records in your organization and store it in the list, suppose the returned Invoice_Statement are larger size
and a large number of them was returned , the heap size limit might be hit


Recommended alternative code for querying within a for loop
To prevent the heap limit error use SOQL for loop, which iterates over the returned results in batches of 200 records. This will reduces the size of the inv list
variable which will now hold the 200 items, instead of all the items in the query result.


So array/list variable size limit is dependent upon the heap size.

Summary: 
  • Avoid using SOQL and DML query inside loop.
  • Use SOQL for loop to avoid heap size limit.
For complete list of apex governor limit, see this Link

Comments

  1. I've run into this issue from legacy code. Thanks for the post.

    ReplyDelete

Post a Comment

Popular Posts