2

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?

1
  • Can you post an actual code? I assume problem is in division of integer numbers, so a/b would be always 0 if a < b, and they are both positive
    – kurunve
    Commented Nov 12, 2019 at 7:11

2 Answers 2

2

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.

0

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.

2
  • 3
    That blog post is incorrect (and thus, this answer is also incorrect). The heap limits are only checked "periodically", and you can exceed this limit for a small period of time. I've managed to hit 138,000,000 bytes of heap used without an exception occurring--in production. It's a lot more complicated than just checking every time there's a heap allocation.
    – sfdcfox
    Commented Nov 12, 2019 at 7:49
  • 1
    Thanks for the correction and the detailed answer @sfdcfox.
    – Atlas Can
    Commented Nov 12, 2019 at 7:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .