This error usually occurs when Apex retrieves too many records, too many fields, or both.
The Apex heap size limit for a synchronous transaction is 6 MB.
To reduce heap usage:
- Query only the records that are actually needed.
- Select only the fields required for processing.
- Avoid selecting unnecessary relationship fields.
- Relationship data is repeated for every returned row, which can significantly increase memory usage.
- When many records reference the same related record, query the related records separately and store them in a
Map<Id, SObject>.
For example, instead of selecting many parent fields in the main query:
SELECT Id, Account.Name, Account.BillingCity, Account.BillingState
FROM ContactQuery only the parent ID:
SELECT Id, AccountId
FROM ContactThen retrieve the required Account data separately and store it in a map:
Map<Id, Account> accountMap = new Map<Id, Account>(
[SELECT Id, Name, BillingCity, BillingState
FROM Account
WHERE Id IN :accountIds]
);This prevents the same relationship data from being stored repeatedly for every row and can significantly reduce heap usage.
Comments
0 comments
Please sign in to leave a comment.