android 判斷字串是否為空的最優方法
阿新 • • 發佈:2019-02-01
public class TestEmptyString { String s = ""; long n = 10000000; private void function1() { long startTime = System.currentTimeMillis(); for (long i = 0; i < n; i++) { if (s == null || s.equals("")) ; } long endTime = System.currentTimeMillis(); System.out.println("function 1 use time: " + (endTime - startTime) + "ms"); } private void function2() { long startTime = System.currentTimeMillis(); for (long i = 0; i < n; i++) { if (s == null || s.length() <= 0) ; } long endTime = System.currentTimeMillis(); System.out.println("function 2 use time: " + (endTime - startTime) + "ms"); } private void function3() { long startTime = System.currentTimeMillis(); for (long i = 0; i < n; i++) { if (s == null || s.isEmpty()) ; } long endTime = System.currentTimeMillis(); System.out.println("function 3 use time: " + (endTime - startTime) + "ms"); } private void function4() { long startTime = System.currentTimeMillis(); for (long i = 0; i < n; i++) { if (s == null || s == "") ; } long endTime = System.currentTimeMillis(); System.out.println("function 4 use time: " + (endTime - startTime) + "ms"); } public static void main(String[] args) { TestEmptyString test = new TestEmptyString(); test.function1(); test.function2(); test.function3(); test.function4(); }
方法一: 最多人使用的一個方法, 直觀, 方便, 但效率很低.
方法二: 比較字串長度, 效率高, 是我知道的最好一個方法.
方法三: Java SE 6.0 才開始提供的辦法, 效率和方法二基本上相等, 但出於相容性考慮, 推薦使用方法二或方法四.
方法四: 這是種最直觀,簡便的方法,而且效率也非常的高,與方法二、三的效率差不多
以下程式碼在我機器上的執行結果: (機器效能不一, 僅供參考)
function 1 use time: 140ms
function 2 use time: 47ms
function 3 use time: 47ms
function 4 use time: 47ms
注意:s == null 是有必要存在的.
如果 String 型別為 null, 而去進行 equals(String) 或 length() 等操作會丟擲java.lang.NullPointerException.
並且s==null 的順序必須出現在前面.不然同樣會丟擲java.lang.NullPointerException.
如下程式碼:
Java程式碼
String str= = null;
if(str=.equals("") || str= == null){//會丟擲異常
System.out.println("success");
}
// "".equales(str);後置確保不會遇null報錯。