java9有那些改进_Java9新特性系列(String改进)

35c765f406160cf50708f3a65ef99473.png

Java9前时代

在Java9之前,String的源码如下:

package java.lang;

public final class String

implements java.io.Serializable, Comparable, CharSequence{

/** The value is used for character storage. */

private final char value[];

...

}

复制代码

可以看到,String的内部是一个char数组,每个字符占2个字节(16位)。

Java9

产生背景:

The current implementation of the String class stores characters in a char array, using two bytes (sixteen bits) for each character. Data gathered from many different applications indicates that strings are a major component of heap usage and, moreover, that most String objects contain only Latin-1 characters. Such characters require only one byte of storage, hence half of the space in the internal char arrays of such String objects is going unused.

大量数据表明,String对象占用了主要的堆使用,而且,大部分的字符串对象只包含Latin-1字符,这样的字符只需要一个字节的存储空间,因此此类字符串对象的内部char数组中的一半空间将被闲置。所以,Java9中对String对存储结构进行了改进:

描述:

We propose to change the internal representation of the String class from a UTF-16 char array to a byte array plus an encoding-flag field. The new String class will store characters encoded either as ISO-8859-1/Latin-1 (one byte per character), or as UTF-16 (two bytes per character), based upon the contents of the string. The encoding flag will indicate which encoding is used.

String改成了byte数组,再加上编码标记,就节约了不少空间。

Java9中String源码如下:

package java.lang;

public final class String

implements java.io.Serializable, Comparable, CharSequence{

/**

* The value is used for character storage.

*

* @implNote This field is trusted by the VM, and is a subject to

* constant folding if String instance is constant. Overwriting this

* field after construction will cause problems.

*

* Additionally, it is marked with {@link Stable} to trust the contents

* of the array. No other facility in JDK provides this functionality (yet).

* {@link Stable} is safe here, because value is never null.

*/

@Stable

private final byte[] value;

...

}

复制代码String-related classes such as AbstractStringBuilder, StringBuilder, and StringBuffer will be updated to use the same representation, as will the HotSpot VM's intrinsic string operations.

与String相关对比如AbstractStringBuilder、StringBuilder、StringBuffer也将有相同的实现,不知道在3月份即将发布的Java10中实现呢,期待~

微信公众号:码上论剑

请关注我的个人技术微信公众号,订阅更多内容

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值