繁体   English   中英

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

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

我有很多需要处理的词,所有这些词都以. ,哪个选项具有最佳时间复杂度?

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

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

  3. word.replace(".", "")

或者,还有更好的方法?

一个简单的测试(使用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.");

}

输出:

子串:0毫秒。

replaceAll:78毫秒。

替换:16毫秒。

正如预期的那样, substring最快,因为:

  1. 它避免编译正则表达式。
  2. 它是常量时间:根据指定的开始和结束索引创建一个新的String

暂无
暂无

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

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