我有很多需要处理的单词并且所有单词都以此结尾.
,哪个选项具有最佳的时间复杂度?
word.substring(0, word.length()-1)
word.replaceAll("\\."?"")
word.replace(".", "")
或者,还有更好的方法?
man*_*uti 14
一个简单的测试(使用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.");
}
Run Code Online (Sandbox Code Playgroud)
输出:
子串:0毫秒.
replaceAll:78毫秒.
替换:16毫秒.
正如所料,这substring
是最快的,因为:
String
基于指定的开始和结束索引创建新的. 归档时间: |
|
查看次数: |
2737 次 |
最近记录: |