String.substring()制作底层char []值的副本 [英] String.substring() making a copy of the underlying char[] value

查看:123
本文介绍了String.substring()制作底层char []值的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String.substring 的性能注意事项有关的问题。在Java 1.7.0_06之前, String.substring()方法返回一个共享相同底层的新 String 对象char数组作为其父项,但具有不同的偏移量和长度。为了避免在只需要保留一个小子字符串时在内存中保留一个非常大的字符串,程序员习惯于编写如下代码:

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));

从1.7.0_06开始,没有必要创建新的字符串因为在Oracle的 String 的实现中,子字符串不再共享其底层字符数组。

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.

我的问题是:我们可以依赖Oracle(和其他供应商)不要回到 char [] 在以后的版本中共享,只需要 s = s.substr(...),或者我们是否应该显式创建一个新的String,以防JRE的未来版本再次开始使用共享实现?

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?

推荐答案

String 的实际表示是一个内部实现细节,所以你永远无法确定。然而,根据甲骨文工程师的公开谈话(最着名的是 @shipilev ),它不太可能被改变。这样做不仅可以解决可能的内存泄漏,还可以简化String内部。使用更简单的字符串,可以更轻松地实现许多优化技术,如字符串重复数据删除 Compact Strings

The actual representation of the String is an internal implementation detail, so you can never be sure. However according to public talks of Oracle engineers (most notably @shipilev) it's very unlikely that it will be changed back. This was done not only to fight with possible memory leak, but also to simplify the String internals. With simpler strings it's easier to implement many optimization techniques like String deduplication or Compact Strings.

这篇关于String.substring()制作底层char []值的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆