关于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 }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值