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
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.
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.
If you are just concatenating values in a known format, consider:
int i = 45;
String str = String.format("%s%d", "dsfgdsgf", i);
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.
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
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.
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.
Related
I need to modify the input string to return some output. Basically, when I see a particular string I need to remove it. I am thinking whether to use StringBuilder versus String. From my perspective, String would be much simpler.
Suppose:
StringBuilder input = new StringBuilder(inputs)
if(inputs.contains("someword)"")) {
// remove it by inputs = inputs.replace("someword", "");
}
Is it better to use StringBuilder input = new StringBuilder(inputs) and delete the particular string or use the original inputs = inputs.replace(...).
I think it will get messy to use StringBuilder. StringBuilder is used for concatentation, but I am not concentating strings.
In the past, StringBuilder was most times much faster than String when you applied multiple modifications to a String.
But since JDK 6, the compiler itself replaces String often automatically by StringBuilder (including all related lines) when this may improve the performance. This becomes visible by the use of a decompiler. So in most cases you won't notice any difference.
If you apply multiple operations to a string in a more complex structure than a simple batch of commands, then using StringBuilder is still better than the automatic compiler optimization.
This question already has answers here:
StringBuilder vs String concatenation in toString() in Java
(20 answers)
Closed 9 years ago.
Onward Java 5,for concatenating string we can use '+' because it internally uses string builder.Is it right.
How?
example:
String a="A";
String b="C";
String a=a+b;
is same as
StringBuilder builder=new StringBuilder("A");
builder.append("B");
Which is efficient?why?
Thank you
The two are functionally the same. Meaning they perform the same task. They are quite different in how they operate behind the scenes.
String concatenation with the + operator will take marginally longer to process because of what happens when it's compiled into bytecode. Without delivering the bytecode here is the code equivalent of concatenation compiled:
// Concatenation
String a = "a";
String b = "b";
a = a + b;
// It's equivalent once it's compiled
String a = "a";
String b = "b";
StringBuilder aBuilder = new StringBuilder(a);
aBuilder.append(b);
a = aBuilder.toString();
As you can see, even though no usage of a StringBuilder is present in the concatenation snippet a StringBuilder is still created and used. This is why (mostly for large data sets where the time will be noticeable) you should avoid concatenation to avoid the need for firing up String builders like this. Just use a builder from the beginning:
StringBuilder a = new StringBuilder("a");
a.append("b");
System.out.println(a);
And you'll save yourself some execution time and memory.
You can easily do a small experiment by setting a breakpoint inside the StringBuilder and then run your program with stringA + stringB.
When I was trying on JDK later than 1.5 this seems to bring me to the breakpoint correctly. Thus I think the proper substitution is done during compile time.
In string + will be used to concat the two string but it will take some time and space which is proportional to length of two strings.
The object StringBuilder has a more efficient way of concatenate Strings. It works similar to ArrayList by allocating predefined array for storing the characters and keeps track of used space. Every time space is exceeded then it will exte
This is same, and there is not much diference, but when you concatenating more that two strings, there is more StringBuilders created. and performance can be low.
I want to create a string which is made by concatenating about 3000 other strings.
I hear that using so many strings can be inefficient because they lie in some kind of
pool and may not be picked up by the GC immediately after they are not needed.
Is this the best way to go about it -
StringBuilder sb = new StringBuilder("");
for(String s : arrayWith3000Strings)
{
sb.append(s);
}
or should i concatenate all the strings into one string ?
This is definitely a case where StringBuilder is preferred.
Strings are "immutable". Any operation that modifies a string (including "append") creates a new string. Using stringbuilder avoids that expense.
This link (one of many) explains further:
http://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html
Yes, Your code is good.
Even though you use String concatenation it creates new String objects because Strings are immutable.
StringBuffer has even better performance than StringBuilder, but StringBuffer is not thread-safe!
EDIT: of course, it is vice versa :)
This question already has answers here:
StringBuilder vs String concatenation in toString() in Java
(20 answers)
How Java do the string concatenation using "+"?
(6 answers)
Closed 8 years ago.
I have worked with String, StringBuilder and StringBuffer in java.
I thought of this question, while I was thinking from efficiency point of view.
Does "+" use in String concatenation affect efficiency?
Yes, but so little it shouldn't matter most of the time.
Using '+' for string constants is the most efficient as the compiler can perform the concatenation.
If you are joining two Strings, the concat method is the most efficient as it avoids using a StringBuilder.
There is almost never a good reason to use StringBuffer except for backward compatibility. StringBuilder or StringWriter are a better choice. However, it is still used explicitly more often than StringBuilder in the JDK :P
StringBuffer is dead, long live StringBuffer
If you're concatenating in a single statement, then it won't matter since the compiler/JIT compiler will automatically optimize it using a StringBuilder.
So "a"+b+"c" will be optimized to (new StringBuilder("a").append(b).append("c")).toString()
However, if you're concatenating a large number of Strings in a loop, definitely explicitly use a StringBuilder as it will significantly speed up your program.
String a = "";
for( int i = 0; i < 1000000; i++ )
a += i;
should be changed to
StringBuilder sb = new StringBuilder();
for( int i = 0; i < 1000000; i++ )
sb.append(i);
String a = sb.toString();
A bit of Yes, But still NO
From the JLS, 15.18.1.2
Optimization of String Concatenation
An implementation may choose to perform conversion and concatenation
in one step to avoid creating and then discarding an intermediate
String object. To increase the performance of repeated string
concatenation, a Java compiler may use the StringBuffer class or a
similar technique to reduce the number of intermediate String objects
that are created by evaluation of an expression.
For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.
In your example:
" Does +" + " use in String concatenation affect efficiency? "
we have to literal Strings, which might be replaced by the compiler, so this will be faster, than StringBuffer/append/toString.
But efficient/faster compared to what? Code execution? Code writing? Code reading?
Since reading a
"Foo = " + foo;
is very easy, I would recommend it, as long as it isn't repeated a million times, or a " s += s2;" repeated a hundret times.
Especially,
System.out.println ("Player " + n + " scores " + player[n].score);
is far better readable than
System.out.println (new StringBuffer ("Player ").append ((Integer.valueOf (n)).toString ().append (" scores ").append (...
Just avoid it in applications which need high performance, or concatenate a very large amount of strings, or a large amount recursively.
If you are using multiple times concatenation with '+' , then yes to some extend. Coz
when you do String a + String b , it actually internally creates a StringBuffer object and use append() of StringBuffer. So every time you do a '+' a new temporary StringBuffer object gets created initialized with "a" and then appended with "b", which then gets converted to a string object.
So if you need multiple concatenation you should rather create a StringBuffer(thread-safe)/StringBuilder(not thread safe) object and keep appending, so that you avoid the creation of StringBuffer objects again and again.
In my project there are some code snippets which uses StringBuffer objects, and the small part of it is as follows
StringBuffer str = new StringBuffer();
str.append("new " + "String()");
so i was confused with the use of append method and the + operator.
ie the following code could be written as
str.append("new ").append("String()");
So are the two lines above same?(functionally yes but) Or is there any particular usage of them? ie performance or readability or ???
thanks.
In that case it's more efficient to use the first form - because the compiler will convert it to:
StringBuffer str = new StringBuffer();
str.append("new String()");
because it concatenates constants.
A few more general points though:
If either of those expressions wasn't a constant, you'd be better off (performance-wise) with the two calls to append, to avoid creating an intermediate string for no reason
If you're using a recent version of Java, StringBuilder is generally preferred
If you're immediately going to append a string (and you know what it is at construction time), you can pass it to the constructor
Actually the bytecode compiler will replace all string concatenation which involve non constants in a Java program with invocations of StringBuffer. That is
int userCount = 2;
System.out.println("You are the " + userCount + " user");
will be rewritten as
int userCount = 2;
System.out.println(new StringBuffer().append("You are the ").append(userCount).append(" user").toString());
That is at least what is observable when decompiling java class files compiled with JDK 5 or 6. See this post.
The second form is most efficient in terms of performance because there is only one string object that is created and is appended to the stringbuffer.
The first form creates three string objects 1) for "new" 2)for "new String" 3) for the concatenated result of 1) and 2). and this third string object is concatenated to the string buffer.
Unless you are working with concurrent systems, use StringBuilder instead of StringBuffer. Its faster but not thread-safe :)
It also shares the same API so its more or less a straight find/replace-