Skip to main content

I'm investigating an unexpected heap behavior when executing Apex code through Execute Anonymous.

In my original implementation, I repeatedly concatenated strings inside a loop:

String content = (String)largeConstraintRule.get('content');

content += rule.Content__c;

largeConstraintRule.put('content', content);

This resulted in the following exception:

System.LimitException: Apex heap size too large: 11134880

 

 

I then changed the implementation to collect string fragments in List<String>, merge them using String.join(parts, ''), and call parts.clear() afterward. 

 

With the modified implementation, Limits.getHeapSize() reached 17,274,637 bytes (approximately 16.47 MiB) during execution, but the code completed successfully. The final heap size was only 9,186,563 bytes (approximately 8.76 MiB)

. 

 

My questions:

  1. Why did the modified code complete successfully despite reporting a heap size of approximately 17.27 MB?
  2. Can garbage collection or temporary object allocations explain this behavior?
  3. How exactly does Apex enforce heap limits when Limits.getHeapSize() reports a value above the configured limit?

Any insights or official documentation explaining this behavior would be greatly appreciated.

Thank you! 

 

#Salesforce Developer

8 risposte
0/9000