Alex Rivera | Logout

Is += more efficient than concat?

Asked 2010-12-01T09:45:53.850
16

I've been reading code produced by other developers on my team, they seem to favor using += for String concatenation, whereas I prefer using .concat() as it feels easier to read.

I'm trying to prepare an argument as to why using .concat() is better, and I'm wondering, is there any difference in efficiency between the two?

Which option "should" we be taking?

public class Stuff {

    public static void main(String[] args) {

        String hello = "hello ";
        hello += "world";
        System.out.println(hello);

        String helloConcat = "hello ".concat("world");
        System.out.println(helloConcat);
    }
}
Edit
Report

1 Answer

3

In terms of readability, I think you are very wrong. + wins over .concat(). If you are using +=, you might want to think about StringBuilder.append keeping the same StringBuilder for the loop.

In terms of performance concat is better than +. so long as you only use one or perhaps two.

In the case of concat, you will end up creating a String object with a correctly sized char[]. It's about as optimal as you can get.

For + javac generates code that constructs a StringBuilder to do the appending and then converts to a String. From 1.5 you create:

  • A StringBuilder (waste)
  • Initial char[] for StringBuilder (waste)
  • If resulting sequence is too long, a second bigger char[] (waste)
  • The resulting String.
  • The String's char[].

However, you rarely see concat used because it is more difficult to read. The performance is almost certainly going to be a drop in the ocean compared to what else is going on (hint: try the back of an envelope before optimising).

answered 2010-12-01T12:08:05.307

Your Answer