java - Is substring or replace faster to remove the last character in a string? -
i have lots of words need processing , of them end ., option has best time complexity?
word.substring(0, word.length()-1)word.replaceall("\\.","")word.replace(".", "")
or, there better way?
a simple test (with jdk1.7.0_75) can show difference:
private static final int length = 10000; public static void main(string[] args) { string[] strings = new string[length]; (int = 0; < length; i++) { strings[i] = "abc" + + "."; } long start = system.currenttimemillis(); (int = 0; < 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(); (int = 0; < strings.length; i++) { string word = strings[i]; word = word.replaceall(".", ""); } end = system.currenttimemillis(); system.out.println("replaceall: " + (end - start) + " millisec."); start = system.currenttimemillis(); (int = 0; < 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, substring fastest because:
- it avoids compiling regular expression.
- it constant-time: creating new
stringbased on specified begin , end indices.
Comments
Post a Comment