Reputation: 3413
What is better
int i = 45;
String str = "dsfgdsgf"+i;
or
int i = 45;
String str = new StringBuilder().append("dsfgdsgf").append(i).toString();
I have read somewhere that StringBuilder is always better than concatenating strings
Upvotes: 1
Views: 135
Reputation: 5344
There shouldn't performance difference in both cases: prooflink. Compiler use StringBuilder implicitly to concatenate String.
Of course 1 case is much more readable than 2 in most cases.
Also no big differences in explicit casting of Integer values:
StringBuilder casting use AbstractStringBuilder#append(int) and explicit casting using String#valueOf(int) call Integer#toString(int) internaly.
Upvotes: 4
Reputation: 5609
Strings in Java are immutable objects. This means by writing String str = "dsfgdsgf"+i;
you are actually creating a new String object and leave the old object for the Garbage Collector.
StringBuilder
on the other hand is a mutable object so that the object is modified. Preferably you should use StringBuilder.append()
or StringBuffer.append()
whenever possible.
Note that StringBuilder
is not synchronized
, while StringBuffer
is.
Upvotes: 2
Reputation: 56792
There is no difference in performance, as the compiler will internally convert the first version to the second one.
Since the first version is more readable you should use it when you concatenate a fixed number of items into a string.
Use StringBuilder
when you append to a string many times, for example in a loop.
Upvotes: 7
Reputation: 3938
Your second option is better because it's impossible to concatenate with a String; therefore the String must be converted first to a StringBuilder before doing the concatenation and then have the result converted back to a String.
Upvotes: 1
Reputation: 823
Yes, StringBuilder is better than concatenating string. When you use following line of code String str = "dsfgdsgf"+i;
it uses StringBuilder internally. So you are just avoiding extra step by using StringBuilder directly.
Upvotes: 1
Reputation: 69369
If you are just concatenating values in a known format, consider:
int i = 45;
String str = String.format("%s%d", "dsfgdsgf", i);
Upvotes: 2
Reputation: 3274
We should be using StringBuilder, if you are modifying a string many times by appending, removing etc.In you case, you are using StringBuilder and again converting it to String.I dont think you are saving much with the second approach,since you are creating a new StringBuilder object and appending and again converting it to String
Upvotes: 1