在Java应用程序中,假设我可以选择以下比较方法
equalsIgnoreCase(String anotherString)
compareToIgnoreCase(String str)
哪一个更快?
Jon*_*eet 32
equalsIgnoreCase
可以快得多.例如,考虑两个以相同的10,000个字符开头的字符串 - 但其中一个字符串最后有一个额外的字符.equalsIgnoreCase
可以马上回来; compareToIgnoreCase
必须迭代到字符串的末尾才能看到差异.
但一般来说,我会选择更好地表达你的意图.这对性能也很有效:假设我说这equalsIgnoreCase
至少和compareToIgnoreCase
它一样快,这意味着你应该尽可能地使用它 - 如果你需要实际的订购,你必须使用它compareToIgnoreCase
.
如果你担心表演...... 测量它
查看java.lang.String的源代码
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true :
(anotherString != null) && (anotherString.count == count) &&
regionMatches(true, 0, anotherString, 0, count);
}
Run Code Online (Sandbox Code Playgroud)
因此,在它逐个字符地查看实际的字符串之前(也以类似的方式发生compareToIgnoreCase
),equalsIgnoreCase
还要检查引用标识和字符长度,这可能会非常快.
归档时间: |
|
查看次数: |
9347 次 |
最近记录: |