is there any difference in performance between these two idioms ?
String firstStr = "Hello ";
String secStr = "world";
String third = firstStr + secStr;
and
String firstStr = "Hello ";
String secStr = "world";
String third = String.format("%s%s",firstStr , secStr);
I know that concatenation with + operator is bad for performance specially if the operation is done a lot of times, but what about String.format() ? is it the same or it can help to improve performance?
Each time strcat calls, the loop will run from start to finish; the longer the string, the longer the loop runs. Until the string is extensive, the string addition takes place very heavy and slow.
tl;dr. Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.
Summary: Using the string concatenation operator is slightly faster than using format string literals. Unless you are performing many hundreds of thousands of string concatenations and need them done very quickly, the implementation chosen is unlikely to make a difference.
StringBuilder is faster, because String. format has to parse the format string (a complex domain specific language).
The second one will be even slower (if you look at the source code of String.format()
you will see why). It is just because String.format()
executes much more code than the simple concatenation. And at the end of the day, both code versions create 3 instances of String
. There are other reasons, not performance related, to use String.format()
, as others already pointed out.
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