V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
lxk11153
V2EX  ›  Java

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

  •  
  •   lxk11153 · Apr 6, 2020 · 2931 views
    This topic created in 2225 days ago, the information mentioned may be changed or developed.
    # 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

    3 replies    2020-04-22 15:47:51 +08:00
    shiyouming91
        1
    shiyouming91  
       Apr 6, 2020   ❤️ 4
    Java 9 引入的 Compact Strings 。主要是为了节省内存。当构造的 String 每个字符都可以用 1 byte 表示的时候,会自动在内部存成每个字符 1 byte,不然像原来一样存成每个字符 2 bytes 。

    https://www.vojtechruzicka.com/java-9-compact-strings/
    Aresxue
        2
    Aresxue  
       Apr 7, 2020
    更省内存呗。。。用 jol 打印下内存布局就知道,以前 Java 主要考虑易用性,现在开始优化语法糖和内存了,变成更好的语言吧
    lxk11153
        3
    lxk11153  
    OP
       Apr 22, 2020
    @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 吗?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2862 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 10:52 · PVG 18:52 · LAX 03:52 · JFK 06:52
    ♥ Do have faith in what you're doing.