+ 3
String or StringBuffer ?
I recently came up with a statement saying "Use StringBuffer instead of String for optimization of program". And I found that under the hood String creates the temporary StringBuffer object for concatenation of String, but then I tried using concat() method of String and realized that no StringBuffer object was created in the intermediate step. So now which one is more preferred concat() method of String or simply using StringBuffer ?
4 odpowiedzi
+ 3
If you concatenate a few String its ok to use String.
If you want concatenate a lot of String you should use StringBuilder if you need thread safe then use StringBuffer.
+ 11
expanding the explanation:
String is an immutable object, meaning it CANNOT be change after it been created
and each time you add to it:
String st = "hello";
st += " world";
you are actually creating a new string in the memory and re-bind the st String.
+ 6
StringBuilder is also possible
+ 4
I made a program what compare the concatenations performance:
https://code.sololearn.com/c369kc5K4RQ2/#java