String.trim()比String.replace()更快吗?

Mei*_*lan 5 java

比方说有一个字符串" world ".此字符串仅在前端和末尾有空白.是trim()replace()吗?

我使用了替换一次,我的导师说不要使用它,因为trim()可能更快.

如果不是,有什么优势trim()replace()

GBl*_*ett 11

如果我们查看方法的源代码:

replace():

 public String replace(CharSequence target, CharSequence replacement) {
    String tgtStr = target.toString();
    String replStr = replacement.toString();
    int j = indexOf(tgtStr);
    if (j < 0) {
        return this;
    }
    int tgtLen = tgtStr.length();
    int tgtLen1 = Math.max(tgtLen, 1);
    int thisLen = length();
    int newLenHint = thisLen - tgtLen + replStr.length();
    if (newLenHint < 0) {
        throw new OutOfMemoryError();
    }
    StringBuilder sb = new StringBuilder(newLenHint);
    int i = 0;
    do {
        sb.append(this, i, j).append(replStr);
        i = j + tgtLen;
    } while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0);
    return sb.append(this, i, thisLen).toString()
}
Run Code Online (Sandbox Code Playgroud)

Vs trim():

public String trim() {
    int len = value.length;
    int st = 0;
    char[] val = value;    /* avoid getfield opcode */
    while ((st < len) && (val[st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样,replace()调用多个其他方法并在整个String过程中进行trim()迭代,同时简单地迭代开始和结束,String直到字符不是空格.因此,在单个方面尝试删除单词前后的空格,trim()效率更高.


我们可以对此进行一些基准测试:

public static void main(String[] args) {
       long testStartTime = System.nanoTime();;
       trimTest();
       long trimTestTime = System.nanoTime() - testStartTime;
       testStartTime = System.nanoTime();     
       replaceTest();
       long replaceTime = System.nanoTime() - testStartTime;           
       System.out.println("Time for trim(): " + trimTestTime);
       System.out.println("Time for replace(): " + replaceTime);            
}

public static void trimTest() {
    for(int i = 0; i < 1000000; i ++) {     
        new String("  string   ").trim();
    }
}
public static void replaceTest() {
    for(int i = 0; i < 1000000; i ++) {     
        new String("  string   ").replace(" ", "");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Time for trim(): 53303903
Time for replace(): 485536597
//432,232,694 difference
Run Code Online (Sandbox Code Playgroud)