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);
}
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With