+ operator
String s = s1 + s2
Behind the scenes, this translates to:
String s = new StringBuilder(s1).append(s2).toString();
Imagine how much extra work he adds if you have s1 + s2 here:
stringBuilder.append(s1 + s2)
instead:
stringBuilder.append(s1).append(s2)
A few lines with +
It is worth noting that:
String s = s1 + s2 + s3 + ... +sN
translates to:
String s = new StringBuilder(s1).append(s2).append(s3)...apend(sN).toString();
concat()
String s = s1.concat(s2);
String creates an array of char[] , which can match either s1 or s2 . Copy s1 and s2 contents to this new array. Actually less work is needed than the + operator.
StringBuilder.append()
It supports the internal char[] array, which grows when necessary. No extra char[] is created if the inside is large enough.
stringBuilder.append(s1.concat(s2))
also works poorly because s1.concat(s2) creates an additional char[] array and copies s1 and s2 it only to copy this new contents of the array into the internal StringBuilder char[] .
In doing so, you should use append() all the time and add raw lines (your first piece of code is correct).
Tomasz Nurkiewicz Apr 09 '12 at 20:00 2012-04-09 20:00
source share