简体   繁体   English

子串或替换更快以删除字符串中的最后一个字符?

[英]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: 一个简单的测试(使用JDK1.7.0_75)可以​​显示差异:

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. 子串:0毫秒。

replaceAll: 78 millisec. replaceAll:78毫秒。

replace: 16 millisec. 替换:16毫秒。

As expected, the substring is fastest because: 正如预期的那样, substring最快,因为:

  1. It avoids compiling a regular expression. 它避免编译正则表达式。
  2. It is constant-time: creating a new String based on the specified begin and end indices. 它是常量时间:根据指定的开始和结束索引创建一个新的String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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