关于substring的char[]共享

我们知道,对于一个较大的String对象假设从中获取一个子串。jdk默认子串的char[]是共享原串的char[]。即子串的char[]是原串的char[]中的一部分,

这样对于一个原串多个子串的情况能够节省非常大空间。

可是也正是由于共享,假设一个非常大的原串在获取一个非常小的子串后,原串不再须要,却由于子串共享了char[]一直不能释放,在非常多时候造成相反

的结果。甚至出现性能上的问题:

參见:https://code.google.com/p/mybatis/issues/detail?id=760

要解决这种情况 ,在jdk6中,我们仅仅能在获取子串后又一次new一个子串的新串使用,以使原串的char[]不再被引用从而高速释放:

String src = "abcdefghijklmnopqrstuvwxyz1234567890-=";

String sub = src.substring(1,4);

sub = new String(sub);

...................................

use sub

这种方式代码晦涩,问题难查。jdk7去掉共享。同一时候jdk7优化了拷贝,利用cpu的simd指令。大部分场景下。jdk7字符串性能是比jdk6好的:

 1950       public String substring(int beginIndex, int endIndex) {
 1951           if (beginIndex < 0) {
 1952               throw new StringIndexOutOfBoundsException(beginIndex);
 1953           }
 1954           if (endIndex > count) {
 1955               throw new StringIndexOutOfBoundsException(endIndex);
 1956           }
 1957           if (beginIndex > endIndex) {
 1958               throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
 1959           }
 1960           return ((beginIndex == 0) && (endIndex == count)) ?

this : 1961 new String(offset + beginIndex, endIndex - beginIndex, value); 1962 }



原文地址:https://www.cnblogs.com/cxchanpin/p/6761453.html