Why Stringbuilder When There Is String

Why StringBuilder when there is String?

String does not allow appending. Each method you invoke on a String creates a new object and returns it. This is because String is immutable - it cannot change its internal state.

On the other hand StringBuilder is mutable. When you call append(..) it alters the internal char array, rather than creating a new string object.

Thus it is more efficient to have:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 500; i ++) {
sb.append(i);
}

rather than str += i, which would create 500 new string objects.

Note that in the example I use a loop. As helios notes in the comments, the compiler automatically translates expressions like String d = a + b + c to something like

String d = new StringBuilder(a).append(b).append(c).toString();

Note also that there is StringBuffer in addition to StringBuilder. The difference is that the former has synchronized methods. If you use it as a local variable, use StringBuilder. If it happens that it's possible for it to be accessed by multiple threads, use StringBuffer (that's rarer)

String vs String builder. which is faster? If stringbuilder then why use string

The advantage of String is that it is immutable: once constructed, the contents of a string instance cannot change anymore. This means that you pass strings by reference without making copies all the time.

For example, suppose you would pass a StringBuilder to a class. Then you could change the contents of that StringBuilder afterwards, and confuse the class. So the class would need to make a copy to make sure that the content doesn't change without it knowing about it. With a String this is not necessary, because a String is immutable.

Now, when you're in the process of building a string, this immutability is actually a problem, because a new String instance must be created for every concatenation. That's why the StringBuilder class exists: it is an auxiliary class which is intended to build strings (hence the name).

In practice, it's often not necessary to use a StringBuilder explicitly. The Java compiler will automatically use a StringBuilder for you when you write things like String result = "some constant" + a + b;. Only with complex building logic (using if and for blocks, for example) you need to do that yourself.

When to use StringBuilder in Java

If you use String concatenation in a loop, something like this,

String s = "";
for (int i = 0; i < 100; i++) {
s += ", " + i;
}

then you should use a StringBuilder (not StringBuffer) instead of a String, because it is much faster and consumes less memory.

If you have a single statement,

String s = "1, " + "2, " + "3, " + "4, " ...;

then you can use Strings, because the compiler will use StringBuilder automatically.

StringBuilder vs String concatenation in toString() in Java

Version 1 is preferable because it is shorter and the compiler will in fact turn it into version 2 - no performance difference whatsoever.

More importantly given we have only 3
properties it might not make a
difference, but at what point do you
switch from concat to builder?

At the point where you're concatenating in a loop - that's usually when the compiler can't substitute StringBuilder by itself.

In Java, when should I prefer String over StringBuilder vice versa?

You should use String, because String objects are cached in an object pool and might deliver better performance when you don't change them.

A StringBuilder is only useful when you keep on concatenating String tokens, which shouldn't be the case in a well normalized database table.

The JVM does all sorts of optimizations and chances are that even if you use concatenation the JVM might rewrite that routine to a StringBuilder version.

Why is StringBuilder much faster than String?

Do you understand how it works internally?

Every time you do stringA += stringB; a new string is created an assigned to stringA, so it will consume memory (a new string instance!) and time (copy the old string + new characters of the other string).

StringBuilder will use an array of characters internally and when you use the .append() method it will do several things:

  • check if there are any free space for the string to append
  • again some internal checks and run a System.arraycopy to copy the characters of the string in the array.

Personally, I think the allocation of a new string every time (creating a new instance of string, put the string, etc.) could be very expensive in terms of memory and speed (in while/for, etc. especially).

In your example, use a StringBuilder is better, but if you need (example) something simple like a .toString(),

public String toString() {
return StringA + " - " + StringB;
}

makes no differences (well, in this case it is better you avoid StringBuilder overhead which is useless here).

Pass-by-value (StringBuilder vs String)

Because when you call speak(name);, inside speak when you do

name = name.concat("4");

it creates a new object because Strings are immutable. When you change the original string it creates a new object,I agree that you are returning it but you are not catching it.

So essentially what you are doing is :

name(new) = name(original) + '4'; // but you should notice that both the names are different objects.

try

String name = "Sam";
name = speak(name);

Of course now I think there is no need to explain why it's working with StringBuilder unless if you don't know that StringBuilder is mutable.

Difference between String and StringBuilder and their internal organization

I dunno. Let's go see:

  • http://www.docjar.com/html/api/java/lang/StringBuilder.java.html
72   public final class StringBuilder
73 extends AbstractStringBuilder
  • http://www.docjar.com/html/api/java/lang/AbstractStringBuilder.java.html
45        * The value is used for character storage.
46 */
47 char[] value;
48
49 /**
50 * The count is the number of characters used.
51 */
52 int count;

===

Is StringBuilder an array of characters too?

Apparently, in this particular implementation.

So, I have a StringBuilder MY_OBJ= "Hello". Now if i try to append characters to the end of MY_OBJ, does it not mean that you are actually creating a new array object and copying all these chars into a new one?

Not necessarily. The array isn't necessarily full (count < value.length), so a new array may not need to be allocated. Ideally, you initialized StringBuilder a capacity so that large enough array was allocated from the start.

StringBuilder sb = new StringBuilder(20);
sb.append("Hello");
...
sb.append(" there");

And another question I have in mind is, how does one mark the end of a StringBuilder? Like in C, we use a "/0"

You don't care - String/StringBuilder will handle it internally.



Related Topics



Leave a reply



Submit