1. 程式人生 > >jdk 源碼閱讀有感(一)String

jdk 源碼閱讀有感(一)String

storage his cache har continue 逆向 enc cte ngs

閑暇之余閱讀 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池中的引用數量。

jdk 源碼閱讀有感(一)String