If you reused the same string to return substrings, what happens when the main string goes out of scope?
In the best case, it will need to remain in memory and cannot be collected until all substrings have been released, so you get more memory.
This is just one of the problems.
In fact, the garbage collector will have several options:
keep the entire source string in memory, even using only a very short substring.
Release the parts of the original string that are not referenced, and keep the substring where it is. This will create a lot of fragmentation, which means that the garbage collector will probably have to move the lines at some point: we will still make a copy.
I am sure that it has its own use cases, and sometimes it can be more efficient when working with substrings (say, when working with large XML documents).
However, as John said, Java string objects require more space, so if you have many small strings, they can actually use more memory than the .Net method.
This is a compromise.
I think that if you are in a situation where it is really important how memory is managed and you need to have absolutely predictable behavior, neither Java nor .NET will be the best tools.
We use garbage collectors because they are optimized for efficient operation in the vast majority of cases.
Knowing how they work is important, but regardless of whether they use row reuse or not, this is more of an optimization left to the underlying platform, and it should not flow too much to the surface. GC, after all, is here to help us.
source share