Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is String.trim() faster than String.replace()?

Tags:

java

Let's say there has a string like " world ". This String only has the blank at front and end. Is the trim() faster than replace()?

I used the replace once and my mentor said don't use it since the trim() probably faster.

If not, what's the advantage of trim() than replace()?

like image 424
Meilan Avatar asked Jun 29 '18 22:06

Meilan


People also ask

Is substring faster than replace?

As expected, the substring is fastest because: It avoids compiling a regular expression.

What is difference between trim and replace?

Trim() and Replace() do not serve the same purpose. Trim() removes all whitespace characters from the beginning and end of the string. That means spaces , tabs , new lines , returns , and other assorted whitespace characters. Replace() only replaces the designated characters with the given replacement.

Why We Use trim () method with the strings?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

Is string replace costly in Java?

As you know, in Java, Strings are immutable. So every time we construct or concatenate a String object, Java creates a new String – this might be especially costly if done in a loop.


1 Answers

If we look at the source code for the methods:

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()
}

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;
}

As you can see replace() calls multiple other methods and iterates throughout the entire String, while trim() simply iterates over the beginning and ending of the String until the character isn't a white space. So in the single respect of trying to only remove white space before and after a word, trim() is more efficient.


We can run some benchmarks on this:

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(" ", "");
    }
}

Output:

Time for trim(): 53303903
Time for replace(): 485536597
//432,232,694 difference
like image 69
GBlodgett Avatar answered Sep 29 '22 19:09

GBlodgett