【发布时间】:2023-04-05 19:07:01
【问题描述】:
在 java 应用程序中,假设我可以选择以下比较方法
equalsIgnoreCase(String anotherString)
compareToIgnoreCase(String str)
哪个更快?
【问题讨论】:
在 java 应用程序中,假设我可以选择以下比较方法
equalsIgnoreCase(String anotherString)
compareToIgnoreCase(String str)
哪个更快?
【问题讨论】:
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);
}
因此,在逐个字符查看实际字符串之前(compareToIgnoreCase 也以类似的方式发生),equalsIgnoreCase 还会检查引用标识和字符长度,这可能会快得多。
【讨论】: