※ 引述《willieliao (Willie Liao)》之銘言:
: 這個是真的,因為.length()是單純傳回String 物件內部那個char array的
: size,performance是O(1)
: "".equals(xxx)是比較hashcode,String這個class有overwrite hashcode()的實作
: 查api就知道hashcode是
: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
: 因此performance是 O(nlogn),length()大勝
: 恩,明天去把公司面試題庫加上這一題 ;p
應該不是吧,
String.equals() 那段程式碼如下:
---
01 public boolean equals(Object anObject) {
02 if (this == anObject) {
03 return true;
04 }
05 if (anObject instanceof String) {
06 String anotherString = (String)anObject;
07 int n = count;
08 if (n == anotherString.count) {
09 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 }
---
所以如果要比較的對象不是空字串,
只會執行到第 8 行,
若是空字串,則 13 行的迴圈也不會進去。
s1.length==0 只需一次判斷
"".equals(s1) 當 s1 為空字串時,需要四次判斷,七次 assign
非空字串時,需要三次判斷,兩次 assign
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.114.78.239
推
04/11 23:09, , 1F
04/11 23:09, 1F
討論串 (同標題文章)