I have a system.debug() that outputs the result of division of the currently used heap space by an integer. It always shows 0.
What could be the root cause of this?
I have a system.debug() that outputs the result of division of the currently used heap space by an integer. It always shows 0.
What could be the root cause of this?
An integer divided by an integer results in an integer, where the fractional part will be discarded. You must convert one of the integer values to a Decimal to get the correct result.
System.debug(3/2); // Outputs 1
System.debug(3.0/2); // Outputs 1.5
To get the correct "percentage" usage of heap, you need to make one of the values a decimal:
System.debug(Limits.getHeapSize()/Decimal.valueOf(Limits.getLimitHeapSize()));
Note that heap is tracked in all orgs (even sandboxes), but it does not automatically trigger the millisecond you hit the heap limit (e.g. 6,000,000). For example, the following code will result in an error in any org:
String[] heap = new String[0];
for(Integer i = 0; i < 50000; i++) {
heap.add('0'.repeat(i*100));
}
Contrariwise, this code should never throw an exception in any org (even production):
String a = '0'.repeat(6000000);
String b = '1'.repeat(6000000);
System.debug(Limits.getHeapSize()); // Outputs at least 12,000,000...
Also, there's some situations where the heap is temporarily tucked away, such as during nested triggers. I go in to a lot more detail in this answer, which I suggest you also take a look at.
Are you on production or sandbox? According to this link, heap size is not tracked by the sandbox environment.
Use Limits to check the values in Apex:
System.debug(LoggingLevel.Debug, 'Heap Size: ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize());
09:43:04:672 USER_DEBUG [155]|DEBUG| Heap Size: 8877586/6000000 Note how the actual Heap Size reported here is greater than the Heap Limit size! This seems to be an oddity of the sandbox environment as in production a LimitException would occur.