Next is a recommendation from Effective Java I am 51. 2
It says beware the performance of string concatenation. 3
Let's see what exactly it has to say. 4
It says a bless operator is a convenient way to combine few strings and it shouldn't be used to combine 5
more than few strengths unless performance is irrelevant. 6
This is because with each concatenation these steps are being performed condense of both strings are 7
first copied then a new String object is created and is appended with both the strings. 8
Finally a new string is generated by invoking the string method on the string builder object. 9
So these steps are being performed with each concatenation. 10
Let's look at an example. 11
Let's assume there is an array with three strings A B and C that are to be concatenated in a for loop 12
. 13
That is each iteration appends a string from the RV to understand the performance implication of using 14
Pless operator. 15
Let's consider the following statements which correspond to each iteration and the follow up. 16
Let's assume s to be a string variable declared outskirt a for loop and is initialized with an empty 17
string. 18
The first statement corresponds to a statement execution during the first iteration and it is a concatenation 19
between an empty string and a string. 20
What does a copy of the string under string ARMH first and then they are concatenated in the second 21
statement string as is up and there will be a copy of the current value of s. 22
Registering a is made along with a copy of B and then the concatenation is performed similarly in the 23
final statement. 24
A copy of the current value of S is made with a string AB along with the copy of C and then the concatenation 25
is performed. 26
Also note that a string builder object is constructed for each of these concatenations. 27
So as you can see it is quite expensive to use plus operator time complexity is quadratic as we have 28
to create a copy of previously created string in each iteration that is and iteration requires a copy 29
or string. 30
Million and minus Vonte iteration. 31
Similarly it is best consuming to add several strings that are getting created along with dust string 32
builder objects. 33
So item 51 recommends to use trng builder as it has a linear complexity. 34
There is only one string builder object can be created out of the follow on in each iteration. 35
A string can be appended to this object according to one benchmark string builder was found to be 300 36
times faster than using plus operator. 37
Similarly string builder was also found to be twice as fast as a string buffer. 38
In this particular benchmark a string is constructed by looping for Iran sixteen thousand five hundred 39
times. 40
If you're interested in this benchmark just look at the link provided in the resource section. 41
And that's about it. 42
So you string builder. 43
If performance is important. 44
Use Pless operator only to combine fuse strings. 45
Thank you