亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么Java String源碼方法regionMatches()不調用其重載實現?

為什么Java String源碼方法regionMatches()不調用其重載實現?

呼啦一陣風 2019-01-16 13:13:46
String源碼里的這兩個方法如下: public boolean regionMatches(int toffset, String other, int ooffset, int len) { char ta[] = value; int to = toffset; char pa[] = other.value; int po = ooffset; // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) || (toffset > (long)value.length - len) || (ooffset > (long)other.value.length - len)) { return false; } while (len-- > 0) { if (ta[to++] != pa[po++]) { return false; } } return true; } public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) { char ta[] = value; int to = toffset; char pa[] = other.value; int po = ooffset; // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) || (toffset > (long)value.length - len) || (ooffset > (long)other.value.length - len)) { return false; } while (len-- > 0) { char c1 = ta[to++]; char c2 = pa[po++]; if (c1 == c2) { continue; } if (ignoreCase) { // If characters don't match but case may be ignored, // try converting both characters to uppercase. // If the results match, then the comparison scan should // continue. char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) { continue; } // Unfortunately, conversion to uppercase does not work properly // for the Georgian alphabet, which has strange rules about case // conversion. So we need to make one last check before // exiting. if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { continue; } } return false; } return true; } 但是,明顯可以這么寫 public boolean regionMatches(int toffset, String other, int ooffset,int len) { return regionMatches(false,toffset, other, ooffset, len); } 但是jdk8里還是這樣分開實現的,是處于什么其他考慮嗎? (話說string里類似的重復實現還有不少)
查看完整描述

1 回答

?
慕少森

TA貢獻2019條經驗 獲得超9個贊

測試程序:

String s1 = "oshagoeutno;shfsSFSDAFsfjgpdhsf;AJofdi1248938jdsgjJDJFSDoghp79874hgajfJDy9(FS*U9prhgdsjfdghnsdfasf";
String s2 = "oshagoeutno;shfsSFSDAFsfjgpdhsf;AJofdi1248938jfogheyjJDJFSDoghp79874hgajfJDy9(FS*U9prhgdsjfdghnsdfasf";
long start = System.nanoTime();
for (int i = 0; i < 10_000_000; i++) {
    s1.regionMatches(5, s2, 5, 65);
}
long end = System.nanoTime();
System.out.println("regionMatches(): " + (end - start));

start = System.nanoTime();
for (int i = 0; i < 10_000_000; i++) {
    s1.regionMatches(false, 5, s2, 5, 65);
}
end = System.nanoTime();
System.out.println("regionMatches(false): " + (end - start));

結果:

regionMatches(): 633992574
regionMatches(false): 805662114

第一個比第二個稍微快一些。

查看完整回答
反對 回復 2019-02-12
  • 1 回答
  • 0 關注
  • 401 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號