String判空效率比較
阿新 • • 發佈:2019-01-26
今天逛社群時忽然看到以下博主時的博文,說字串判空的效率,覺得口說無憑,於是自己手動測試了一下,以下是我的測試程式碼,不足之處,還望大神指教
http://blog.csdn.net/fengxuezhiye/article/details/7763384
1.下面是測試100萬次的程式碼
1 package testData; 2 3 public class TestData { 4 public static void main(String[] args) { 5 //不需要匯入包 6 //在你的方法第一行加上: 7 //long a=System.currentTimeMillis();8 //在最好的一行加上: 9 //System.out.println("\r<br>執行耗時 : "+(System.currentTimeMillis()-a)/1000f+" 秒 "); 10 String name=""; 11 String name2="aa"; 12 String name3=null; 13 // 測試空 14 long a=System.currentTimeMillis(); 15 for(int i=0;i<1000000;i++){ 16 if(name == null || name.equals("")){ 17 18 } 19 } 20 System.out.println("\r<br>執行耗時 : "+(System.currentTimeMillis()-a)/1000f+" 秒 "); 21 // 測試長度 22 long a2=System.currentTimeMillis(); 23 for(int i=0;i<1000000;i++){24 if(name == null || name.length() <= 0){ 25 26 } 27 } 28 System.out.println("\r<br>執行耗時 : "+(System.currentTimeMillis()-a2)/1000f+" 秒 "); 29 } 30 }
以下是三次執行的效果
(1)
(2)
(3)
2.下面是1萬次的測試結果
3.結果 事實證明 比較長度確實比比較空效率 高
但是我不甘心如此,又去網上搜了其他資料
以下是蒐集的資料
1.關於String str = “abc” 的內部工作。Java內部將此語句轉化為以下多個 步驟:
(1 )先定義一個名為str的對String類的物件引用變數:String str;
(2 )在棧中查詢有沒有存放值為 “abc” 的地址,如果沒有,則開闢一個存放字面值為 “abc” 的地址,接著建立 一個新的String類的物件o,並將o的字串值指向這個地址,而且在棧中這個地址旁邊記下這個引用的物件o。如果已經有了值為 “abc” 的地址,則查詢物件o,並返回o的地址。
(3 )將str指向物件o的地址。
值得留心 的是,一般String類中字串值都是直接存值的。但像String str = “abc” ;這種場合下,其字串值卻是儲存了一個指向存在棧中資料的引用!
2.官方的String的equals的重寫原始碼
1 public boolean equals(Object anObject) { 2 if (this == anObject) { 3 return true; 4 } 5 if (anObject instanceof String) { 6 String anotherString = (String)anObject; 7 int n = count; 8 if (n == anotherString.count) { 9 char v1[] = value; 10 char v2[] = anotherString.value; 11 int i = offset; 12 int j = anotherString.offset; 13 while (n-- != 0) {//看到這忽然就明白了 14 if (v1[i++] != v2[j++]) 15 return false; 16 } 17 return true; 18 } 19 } 20 return false; 21 }
瞬間明朗了,吃飯!