I have a apex remote action method which expects a string as parameter.But I have to validate if the byte size of the string value that I received exceeds a certain amount or not in the apex code.Is there a way to determine the byte size of a string in apex?


There are 2 possible cases:

Integer prev = 0;
prev = Limits.getHeapSize(); // we are doing it after allocating memory on Integer
String toCheck = '😁1a';
Integer curr = Limits.getHeapSize(); // we are doing it right in time of Integer initialization to ensure we have the heap size right after allocating space for String
system.debug(curr - prev); // 4
system.debug(Blob.valueOf(toCheck).size()); // 6

Blob size counts it as 6, however, I'm mostly attached to the solution with heap size, for me it is more accurate (as you see, 1 byte per ordinary character, 2 bytes for emoji).

I have also added comment with link to the question that I think will be useful for you to check.


Not the answer you're looking for? Browse other questions tagged or ask your own question.