4

I wants to know what the size of string/blob in apex. What i found is just size() method, which return the number of characters in string/blob. What the size of single character in Salesforce ? Or there is any way to know the size in bytes directly ?

hcohen
  • 325
  • 6
  • 17

2 Answers2

0

I think the only real answer here is "it depends". Why do you need to know this?

  • The methods on String like charAt and codePointAt suggest that UTF-16 might be used internally; in that case, each character would be represented by 2 or 4 bytes, but this is hardly "proof".

  • Apex seems to be translated to Java and running on some form of JVM and Strings in Java are represented internally as UTF-16 so again that could indicate that characters are 2 or 4 bytes in Apex.

  • Any time Strings are sent over the wire (e.g. as responses from a @RestResource annotated class), UTF-8 seems to be used as a character encoding, which would mean 1 to 4 bytes per character are used, depending on what character it is. (See section 2.5 of the Unicode standard.)

But you should really ask yourself why you think your code needs to know this because it most likely doesn't matter.

Frans
  • 3,670
  • 1
  • 31
  • 29
0

You can estimate string size doing the following:

String testString = 'test string';
Blob testBlob = Blob.valueOf(testString);

// below converts blob to hexadecimal representation; four ones and zeros 
// from blob will get converted to single hexadecimal character
String hexString = EncodingUtil.convertToHex(testBlob);

// One byte consists of eight ones and zeros so, one byte consists of two 
// hex characters, hence the number of bytes would be
Integer numOfBytes = hexString.length() / 2;

Another option to estimate the size would be to get the heap size before and after assigning value to String variable:

String testString;
System.debug(Limits.getHeapSize());
testString = 'testString';
System.debug(Limits.getHeapSize());

The difference between two printed numbers would be the size a string takes on the heap.

Please note that the values obtained from those methods will be different. We don't know what type of encoding is used for storing string in Salesforce heap or when converting string to blob.