Java .lang.String#value 从 char[]变到 byte[]有啥用意吗?

2020-04-06 04:51:33 +08:00
 lxk11153
# java 8
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
# java 10
public final class String
    implements java.io.Serializable, Comparable<String>, 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;

ps: 不知道哪个版本变的,没去看 java 9

2398 次点击
所在节点    Java
3 条回复
shiyouming91
2020-04-06 08:30:50 +08:00
Java 9 引入的 Compact Strings 。主要是为了节省内存。当构造的 String 每个字符都可以用 1 byte 表示的时候,会自动在内部存成每个字符 1 byte,不然像原来一样存成每个字符 2 bytes 。

https://www.vojtechruzicka.com/java-9-compact-strings/
Aresxue
2020-04-07 09:17:03 +08:00
更省内存呗。。。用 jol 打印下内存布局就知道,以前 Java 主要考虑易用性,现在开始优化语法糖和内存了,变成更好的语言吧
lxk11153
2020-04-22 15:47:51 +08:00
@shiyouming91 #1 那里面说的"Depending on which characters it contains, it will either use UTF-16 or Latin-1, that is - either one or two bytes per character."
是不是有点问题啊? Latin-1: one byte per character 没问题
UTF-16 是 two bytes per character 吗?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/659733

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX