简体   繁体   中英

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM