我有很多需要处理的单词,所有单词都以.
结尾,
哪个选项具有最佳时间复杂度?
word.substring(0, word.length()-1)
word.replaceAll("\\.","")
word.replace(".", "")
或者,有更好的方法吗?
答案 0 :(得分:13)
简单测试(使用JDK1.7.0_75)可以显示差异:
private static final int LENGTH = 10000;
public static void main(String[] args) {
String[] strings = new String[LENGTH];
for (int i = 0; i < LENGTH; i++) {
strings[i] = "abc" + i + ".";
}
long start = System.currentTimeMillis();
for (int i = 0; i < strings.length; i++) {
String word = strings[i];
word = word.substring(0, word.length()-1);
}
long end = System.currentTimeMillis();
System.out.println("substring: " + (end - start) + " millisec.");
start = System.currentTimeMillis();
for (int i = 0; i < strings.length; i++) {
String word = strings[i];
word = word.replaceAll(".", "");
}
end = System.currentTimeMillis();
System.out.println("replaceAll: " + (end - start) + " millisec.");
start = System.currentTimeMillis();
for (int i = 0; i < strings.length; i++) {
String word = strings[i];
word = word.replace(".", "");
}
end = System.currentTimeMillis();
System.out.println("replace: " + (end - start) + " millisec.");
}
输出:
substring:0 millisec。
replaceAll:78毫秒。
替换:16毫秒。
正如预期的那样,substring
是最快的,因为:
String
。