Is there a limit to the maximum key size for a map in Apex?

Say if I have Map<String, SObject>, how long can the string key be?

  • I suspect the answer is "practically no limit" and "the ultimate determining factor is the size of the heap"
    – Derek F
    Jul 6, 2023 at 18:18

2 Answers 2


This is easy enough to test.

Map<String, Integer> testMap = new Map<String, Integer>();
// a string 5.5 million characters long
String testKey = 'a'.repeat(5500000);
testMap.put(testKey, 1);
System.debug(testMap.get(testKey)); // prints 1

The above works just fine.

You could take this particular example to about 5.99 million characters (you need to reserve some heap space for the map, the value you store in the map, etc...), and after that you run into the heap limit.

  • I did some tests but couldn't get a definite answer. This is great, thank you!
    – Arthlete
    Jul 6, 2023 at 18:31
  • 1
    You forgot about asynchronous limits...
    – sfdcfox
    Jul 6, 2023 at 19:16

The maximum length is actually Limits.getLimitHeapSize(). That's because the maximum length of a string is limited to this value. You can temporarily exceed this limit across multiple objects, but doing this in a single string is not allowed; you'd get a String exception with the message stating that the string is too long.

You must log in to answer this question.

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