Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is += more efficient than concat? [duplicate]

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);
    }
}
like image 630
Jimmy Avatar asked Dec 01 '10 09:12

Jimmy


2 Answers

Since String is immutable in java, when you do a +, += or concat(String), a new String is generated. The bigger the String gets the longer it takes - there is more to copy and more garbage is produced.

Today's java compilers optimizes your string concatenation to make it optimal, e.g.

System.out.println("x:"+x+" y:"+y);

Compiler generates it to:

System.out.println((new StringBuilder()).append("x:").append(x).append(" y:").append(y).toString());

My advice is to write code that's easier to maintain and read.

This link shows performance of StringBuilder vs StringBuffer vs String.concat - done right

like image 198
Buhake Sindi Avatar answered Oct 17 '22 01:10

Buhake Sindi


It shouldn't matter. Modern day Java compilers, JVMs and JITs will optimize your code in such a way that differences are likely to be minimal. You should strive to write code that's more readable and maintainable for you.

like image 38
darioo Avatar answered Oct 17 '22 03:10

darioo