Java String提高比較效率

java對兩個String進行比較,提高代碼運行效率方法如下:

在編程過程中,有時候我們需要循環比較字符串,通常使用的方法是equals如下:

public class TestEquals extends Thread {
    public static void main(String args[]) {
        String[] checkStr = {"","aaaa","bbbb","sdf","dsdf"};
        String str="DingDong";
        for(int i=0;i<checkStr.length;i++){
            if(str.equals(checkStr[i])){//比較字符串
                System.out.println("DingDong has in the checkStr list!");

                break;
            }
        }
    }
}

而equals的源代碼如下:

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = count;
            if (n == anotherString.count) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = offset;
                int j = anotherString.offset;
                while (n-- != 0) {
                    if (v1[i++] != v2[j++])
                        return false;
                }
                return true;
            }
        }
        return false;
    }

我們可以看到,要得到字符串完全相同,必須進行如下操作:1)比較是否是同一個個對象:" if (this == anObject) {"; 2)是否是同類型對象:“if (anObject instanceof String) {”; 3)轉換字符串,判斷字符串長度是否相同:“if (n == anotherString.count) {”; 4)分解字符串一一比較。 最終返回boolean值。

通過以上分析,字符串比較經過了4補的操作最終獲得結果值。

而當我們知道兩個需要比較的對象都是字符串String 時,可以對其代碼進行優化!優化後結果如下:

public static void main(String args[]) {
        String[] checkStr = { "", "aaaa", "bbbb", "sdf", "dsdf" };
        String str = "DingDong";
        int strL = str.length();
        for (int i = 0; i < checkStr.length; i++) {
            if(checkStr[i]!=null&&strL==checkStr[i].length()){//先判斷長度,減少直接調用equals方法
                if (str.equals(checkStr[i])) {// 比較字符串
                    System.out.println("DingDong has in the checkStr list!");
                    break;
                }
            }
        }
    }

當我們需要比較的字符串數組非常大時,比如有上千個String[1000]對象,而且每個字符串對象都比較長時,其性能效果就會比較明顯了。

方法避免了過多的重複使用equals方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章