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

  • A+
Category:Languages

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

 


If we look at the source code for the methods:

 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 whitespace. So in the single respect of trying to only remove whitespace 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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: