java - Is += more efficient than concat? -
this question has answer here:
i've been reading code produced other developers on team, seem favor using +=
string concatenation, whereas prefer using .concat()
feels easier read.
i'm trying prepare argument why using .concat()
better, , i'm wondering, there difference in efficiency between two?
which option "should" 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 immutable in java, when +
, +=
or concat(string)
, new string generated. bigger string gets longer takes - there more copy , more garbage produced.
today's java compilers optimizes string concatenation make optimal, e.g.
system.out.println("x:"+x+" y:"+y);
compiler generates to:
system.out.println((new stringbuilder()).append("x:").append(x).append(" y:").append(y).tostring());
my advice write code that's easier maintain , read.
this link shows performance of stringbuilder vs stringbuffer vs string.concat - done right
Comments
Post a Comment