My question regards a situation when a split or other String method is called multiple times for the same String object.
Does any popular JVM implementations optimize such calls by storing the results in the memory to be reused later?
It could work like that:
Because of the Strings immutable nature and existence of the String pool an expression
String resource = "A:B:C";
String[] resourceArr = resource.split(":");
would use the same String object references to “A:B:C” and “:” every time it is used. The JVM could match a stored result using those references and provide it without performing the actual parsing.
No. That’d be tremendously wasteful of memory — it’d be extremely rare that the same split results would need to get reused, much less the overhead on a per-String basis — and it’s much better for the programmer to selectively decide when to cache such results, the “normal way.”