String character limit apex

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_primitives.htm enter image description here

There is no character limit specification. In terms of heap size, you have 6MB to work with in synchronous apex vs. 12MB in asynchronous apex.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm

How is heap size calculated?

The answer to that question goes into detail about how heap size is calculated. Based on that, your 1 million character string in of itself is fine, but it'll also depend on what else you're doing in that transaction that would add to the heap size.


Yes! anything and everything you declare gets added to the heap size. Even private declarations inside methods are added to heap size.

Lets consider an example of below 2 approaches where you declare local private strings in method which essentially does same thing. Only difference is that we declare more number of strings in 1 approach.

Approach 1: Declare 3 strings - s1, s2, s3

@AuraEnabled
public static void testHeap3() {
    try {
        System.debug('Init => '+Limits.getHeapSize());
        Integer maxHeap = Limits.getLimitHeapSize();
        System.debug('maxHeap => '+maxHeap);
        String s1 = ' Random ';
        String s2 = ' Text ';
        String s3 = (s1+s2).trim();
        System.debug('Final when 3 string declared => '+Limits.getHeapSize());
        if(Limits.getHeapSize() >= maxHeap) throw new AuraHandledException('Max size reached');
    }
    catch (Exception ex) {
        System.debug(ex.getMessage());
    }
}

Debugs:

enter image description here

Approach 2: Declare 1 string - s1

@AuraEnabled
public static String testHeap1() {
    try {
        System.debug('Init => '+Limits.getHeapSize());
        Integer maxHeap = Limits.getLimitHeapSize();
        System.debug('maxHeap => '+maxHeap);
        String s1 = (' Random '+' Text ').trim();
        System.debug('Final when 1 String declared => '+Limits.getHeapSize());
        if(Limits.getHeapSize() >= maxHeap) throw new AuraHandledException('Max size reached');
        return s1;
    }
    catch (Exception ex) {
        throw new AuraHandledException(ex.getMessage());
    }
}

Debugs:

enter image description here

As you see, the heap size is 1129 when 3 strings declared against the heap size of only 1115 for 1 string declared. So, it is better to minimise number of declarations of local variables and also use getHeapSize and getLimitHeapSize from Limits class along with try...catch blocks as shown in the aproaches.

Tags:

Json

Apex