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?
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(Limits.getHeapSize());
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.
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.