A question relating to performance considerations for String.substring
. Prior to Java 1.7.0_06, the String.substring()
method returned a new String
object that shared the same underlying char array as its parents but with different offset and length. To avoid keeping a very large string in memory when only a small substring was needed to be kept, programmers used to write code like this:
s = new String(queryReturningHugeHugeString().substring(0,3));
From 1.7.0_06 onwards, it has not been necessary to create a new String
because in Oracle's implementation of String
, substrings no longer share their underlying char array.
My question is: can we rely on Oracle (and other vendors) not going back to char[]
sharing in some future release, and simply do s = s.substr(...)
, or should we explicitly create a new String just in case some future release of the JRE starts using a sharing implementation again?