3 ms·
String in Java share their memory with other substrings of the same allocation. They are views.
by rrobukef 4y ago
String in Java share their memory with other substrings of the same allocation. They are views.
- cesarb 4y agoIIRC, that used to be the case, but recent Java releases changed it so that memory is no longer shared with substrings. The former behavior could cause some extreme memory leaks (unless you were very careful to always manually duplicate each substring); a one-character substring could keep a multi-megabyte memory allocation alive. See for instance https://stackoverflow.com/questions/33893655/string-substring-making-a-copy-of-the-underlying-char-value https://stackoverflow.com/questions/33893655/string-substrin... which discusses this issue.
- masklinn 4y agoThat was changed years ago (the slicing optimisation was removed in Java 7 or something) because it caused too many memory leaks. It was also a (bad) optimisation, it was never part of the langage model or semantics.