I have lots of words that need processing and all of them end with .
,
Which option has the best time complexity?
word.substring(0, word.length()-1)
word.replaceAll("\\.","")
word.replace(".", "")
Or, is there a better way?
A simple test (with JDK1.7.0_75) can show the difference:
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.");
}
Output:
substring: 0 millisec.
replaceAll: 78 millisec.
replace: 16 millisec.
As expected, the substring
is fastest because:
String
based on the specified begin and end indices.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With