Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.format() vs string concatenation performance

Tags:

java

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?

like image 471
Leo Avatar asked Feb 16 '14 00:02

Leo


People also ask

Is string concatenation slow?

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.

Is it good to use string format?

tl;dr. Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.

Are F strings faster than concatenation?

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.

Is string format faster than StringBuilder?

StringBuilder is faster, because String. format has to parse the format string (a complex domain specific language).


1 Answers

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.

like image 116
peter.petrov Avatar answered Sep 19 '22 13:09

peter.petrov