Java String提高比較效率

來源:互聯網
上載者:User

http://blog.csdn.net/chenhui1219/article/details/5628843#comments

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方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.