Java 判斷字符串是否爲空的三種方法性能比較

以下是 Java 判斷字符串是否爲空的三種方法.

 

方法一: 最多人使用的一個方法, 直觀, 方便, 但效率很低.
方法二: 比較字符串長度, 效率高.

 

方法三: Java SE 6.0 纔開始提供的方法, 效率和方法二幾乎相等, 但出於兼容性考慮, 推薦使用方法二.

 

以下代碼在我機器上的運行結果: (機器性能不一, 僅供參考)
method 1 use time: 156ms
method 2 use time: 32ms
method 3 use time: 31ms


package test;

import junit.framework.TestCase;


public class JavaTest extends TestCase {
   
    //字符空判斷
    public void CompareStringNothing(){
        String str = "";
        long len = 10000000;

        long startTime1 = System.currentTimeMillis();
        //1
        for(long i = 0; i < len; i++) {
            //此方法最慢
            if(str == null || str.equals(""));
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("method 1 use time: "+ (endTime1 - startTime1) +"ms");

       




    
        long startTime2 = System.currentTimeMillis();
        for(long i = 0; i < len; i++) {
            if(str == null || str.length() <= 0);
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("method 2 use time: "+ (endTime2 - startTime2) +"ms");

       





        long startTime3 = System.currentTimeMillis();         
        for(long i = 0; i < len; i++) {
            if(str == null || str.isEmpty());
        }
        long endTime3 = System.currentTimeMillis();
        System.out.println("method 3 use time: "+ (endTime3 - startTime3) +"ms");

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