Is substring or replace faster to remove the last character in a string?

Is substring or replace faster to remove the last character in a string?

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? 

Solutions/Answers:

Answer 1:

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:

  1. It avoids compiling a regular expression.
  2. It is constant-time: creating a new String based on the specified begin and end indices.

References