If you use the trim source code and rewrite it a bit, you can remove the unused (in your case) substring method:
cropping source code:
public String trim() { int len = value.length; int st = 0; char[] val = value; while ((st < len) && (val[st] <= ' ')) { st++; } while ((st < len) && (val[len - 1] <= ' ')) { len--; } return ((st > 0) || (len < value.length)) ? substring(st, len) : this; }
Test:
public static char[] value = new char[]{' ', ' ', 't', 'w', 's', ' ', ' ', ' '}; public static void main(String[] args) { normal(); optimized(); } public static void normal() { long start = System.nanoTime(); String s = new String(value).trim(); System.out.println("normal : '" + s + "' " + (System.nanoTime() - start) + "ns"); } public static void optimized() { long start = System.nanoTime(); int len = value.length; int st = 0; char[] val = value; while ((st < len) && (val[st] <= ' ')) { st++; } while ((st < len) && (val[len - 1] <= ' ')) { len--; } String s = new String(value, st, len - st); System.out.println("optimized: '" + s + "' " + (System.nanoTime() - start) + "ns"); }
Exit:
run: normal : 'tws' 41656ns optimized: 'tws' 7546ns
So, your new version of the trimmed string will save you some time.
source share