jdk 源码阅读有感(一)String

闲暇之余阅读 jdk 源码。

(一)核心属性

    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

String的核心结构,char型数组与 int 型 hash值。

(二)构造器

构造器方面,由于上述两个值是不可更改的,所以直接 对 String 构造,其实是没有用的,只不过是加上了一个引用。

    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }

对 char 类型数组使用构造方法时,则会借用调用相关的复制数组的操作,对String的底层抽象,字符数组进行赋值。

    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

//
System.arraycopy(original, 0, copy, 0, len); //一个native方法,用于复制数组。
 

(三)方法内常用边界判断

if ((ooffset < 0) || (toffset < 0)
                || (toffset > (long)value.length - len)
                || (ooffset > (long)other.value.length - len)) {
            return false;
        }

连续的 ‘或’ 判断,采用逆向思维对边界判断。

 即判断当前字符串长度的长度减去开始位置后,与参数字符串的长度进行比较,判断边界条件。 

(四)Continue 或 break 的少用用法

startSearchForLastChar:
        while (true) {
            while (i >= min && source[i] != strLastChar) {
                i--;
            }
            if (i < min) {
                return -1;
            }
            int j = i - 1;
            int start = j - (targetCount - 1);
            int k = strLastIndex - 1;

            while (j > start) {
                if (source[j--] != target[k--]) {
                    i--;
                    continue startSearchForLastChar;
                }
            }
            return start - sourceOffset + 1;
        }

设置好需要跳转的点,条件符合后进行跳转。

(五)代码性能提升————减少getField操作。

public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */

        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }
}

value是String中的全局字符数组,在方法内部使用局部变量,得到字符数组的引用,可以有效地减少getField操作。从而提高代码运行效率。

参考:https://blog.csdn.net/gaopu12345/article/details/52084218

(六)intern()方法

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned.

Otherwise, this  String object is added to the pool and a reference to this code String object is returned.

intern方法用于减少String对象引用,实质上是减少String池中的引用数量。

猜你喜欢

转载自www.cnblogs.com/Junpb/p/10840161.html