您的位置:首页 > 其它

关于substring的char[]共享

2014-11-03 09:09 106 查看
我们知道,对于一个较大的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       }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: