function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Giorgos GalaiosGiorgos Galaios 

Heap Size and Substring Issue

We have the following code:
System.debug(Limits.getHeapSize());
String one = '1234567890'.repeat(myRepeater);
System.debug(Limits.getHeapSize());
String oneLine = '1234567890';
System.debug(Limits.getHeapSize());
integer count = 1;
while(one.indexOf(oneLine)>-1){
    System.debug('Count is: ' + count);
    System.debug(Limits.getHeapSize());
    System.debug('one is before: ' + one);
    one = one.subStringAfter(oneLine);
    System.debug('one is after: ' + one);
    System.debug(Limits.getHeapSize());
    count = count+1;
}
System.debug('Finish: ' + Limits.getHeapSize());

When myRepeater is less than 270000, in fact if it is a bit less than Heap Size/20, then the procedure moves on, and we get CPU time limit exception which is expected.

Heap size/20 is calculated as:
270000 * 10 (length of '123456789') = 2700000 * 2 = 5400000 < Governor Limit

But if it is larger, although when starting Heap size is lower than this limit and despite the fact that when in progress, heap size gets less, there is a point in the start that we hit the subStringAfter Heap size limit.
Is this logical?
Has anybody get into this situation?
Since size of string gets reduced, as well as heap size seems to get reduced, shouldn't it be expected not to hit the limit?