5

In my program I need to convert char[] of fixed size into trimmed String (without blank spaces taken from an array). At the moment I do new String(array).trim() but I would like to avoid trim() if possible. Any advice how to do it better? Best Regards.

Farvardin
  • 5,336
  • 5
  • 33
  • 54
Enzomatric
  • 487
  • 8
  • 19

2 Answers2

7

but I would like to avoid trim() if possible. Any advice how to do it better?

Do not look for any alternative and trim() is smart enough which uses substring() method internally. That is fast enough.

Any looping or reg-ex based solutions will hit you hard.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

If you use trim source code and rewrite it a little bit, you can remove unused (in your case) substring method:

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

The output:

run:
normal   : 'tws' 41656ns
optimized: 'tws' 7546ns

So, your version of new trimmed string will save you some time.

Alexey Odintsov
  • 1,705
  • 11
  • 13