The fastest way to convert char [] to a trimmed string

In my program, I need to convert a char[] fixed size to a trimmed String (without spaces taken from the array). At the moment I am doing new String(array).trim() , but I would like to avoid trim() if possible. Any advice on how to make this better? Best wishes.

+5
source share
2 answers

but I would like to avoid trim () if possible. Any advice on how to make this better?

Don't look for alternatives, and trim() is smart enough that uses the substring() method inside. It is fast enough.

Any loop or registry based solutions will hit you hard.

+7
source

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

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; /* avoid getfield opcode */ 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.

+3
source

Source: https://habr.com/ru/post/1200730/


All Articles