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?

  1. word.substring(0, word.length()-1)

  2. word.replaceall("\\.","")

  3. 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:

  1. it avoids compiling regular expression.
  2. it constant-time: creating new string based on specified begin , end indices.

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -