Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 577
1a1a11a Avatar asked May 30 '15 18:05

1a1a11a


1 Answers

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.
like image 95
M A Avatar answered Oct 20 '22 11:10

M A