Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About the String#substring() method

If we take a look at the String#substring method implementation :

new String(offset + beginIndex, endIndex - beginIndex, value);

We see that a new String is created with the same original content (parameter char [] value).

So the workaround is to use new String(toto.substring(...)) to drop the reference to the original char[] value and make it eligible for GC (if no more references exist).

I would like to know if there is a special reason that explain this implementation. Why the method doesn't create herself the new shorter String and why she keeps the full original value instead?

The other related question is : should we always use new String(...) when dealing with substring?

like image 386
alain.janinm Avatar asked May 02 '26 22:05

alain.janinm


1 Answers

I would like to know if there is a special reason that explain this implementation. Why the method doesn't create herself the new shorter String and why she keeps the full original value instead?

Because in most use-cases it is faster for substring() to work this way. At least, that's what Sun / Oracle's empirical measurements would have shown. By doing this, the implementation avoids allocating a backing array and copying characters to the array.

This is only a non-optimization if you have to then copy the String to avoid a memory leakage problem. In the vast majority of cases, the substrings become garbage in a relatively short period of time, and there is no long-term leakage of memory.


Hypothetically, the Java designers could have provided two versions of substring, one which behaved as currently, and the other that created a String with its own backing array. But that would encourage the developer to waste brain-cycles thinking about which version to use. And then there's the problem of utility methods that build on substrings ... like the Pattern / Matcher classes for instance. So I think it is a good thing that they didn't.

like image 60
Stephen C Avatar answered May 04 '26 12:05

Stephen C