Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why StringBuilder when there is String?

I just encountered StringBuilder for the first time and was surprised since Java already has a very powerful String class that allows appending.

Why a second String class?

Where can I learn more about StringBuilder?

like image 259
an00b Avatar asked Mar 08 '11 14:03

an00b


People also ask

What is the best reason for StringBuilder instead of string?

Option C is correct and the primary reason to use StringBuilder. String often creates a new object each time you call certain methods on the object like concat() . StringBuilder optimizes operations like append() because it is mutable.

What is the point of StringBuilder?

StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

What is difference between string builder and StringBuffer?

StringBuilder vs StringBuffer in Java StringBuffer is synchronized. This means that multiple threads cannot call the methods of StringBuffer simultaneously. StringBuilder is asynchronized. This means that multiple threads can call the methods of StringBuilder simultaneously.

Is string builder faster than StringBuffer?

Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable. StringBuffer and StringBuilder are similar, but StringBuilder is faster and preferred over StringBuffer for the single-threaded program. If thread safety is needed, then StringBuffer is used.


9 Answers

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)

like image 130
Bozho Avatar answered Sep 30 '22 09:09

Bozho


Here is a concrete example on why -

int total = 50000;
String s = ""; 
for (int i = 0; i < total; i++) { s += String.valueOf(i); } 
// 4828ms

StringBuilder sb = new StringBuilder(); 
for (int i = 0; i < total; i++) { sb.append(String.valueOf(i)); } 
// 4ms

As you can see the difference in performance is significant.

like image 26
Amir Raminfar Avatar answered Oct 04 '22 09:10

Amir Raminfar


String class is immutable whereas StringBuilder is mutable.

String s = "Hello";
s = s + "World";

Above code will create two object because String is immutable

StringBuilder sb = new StringBuilder("Hello");
sb.append("World");

Above code will create only one object because StringBuilder is not immutable.

Lesson: Whenever there is a need to manipulate/update/append String many times go for StringBuilder as its efficient as compared to String.

like image 26
Umesh K Avatar answered Oct 01 '22 09:10

Umesh K


StringBuilder is for, well, building strings. Specifically, building them in a very performant way. The String class is good for a lot of things, but it actually has really terrible performance when assembling a new string out of smaller string parts because each new string is a totally new, reallocated string. (It's immutable) StringBuilder keeps the same sequence in-place and modifies it (mutable).

like image 29
Rex M Avatar answered Oct 03 '22 09:10

Rex M


The StringBuilder class is mutable and unlike String, it allows you to modify the contents of the string without needing to create more String objects, which can be a performance gain when you are heavily modifying a string. There is also a counterpart for StringBuilder called StringBuffer which is also synchronized so it is ideal for multithreaded environments.

The biggest problem with String is that any operation you do with it, will always return a new object, say:

String s1 = "something";
String s2 = "else";
String s3 = s1 + s2; // this is creating a new object.
like image 25
CarlosZ Avatar answered Sep 30 '22 09:09

CarlosZ


StringBuilder is good when you are dealing with larger strings. It helps you to improve performance.

Here is a article that I found that was helpful .

A quick google search could have helped you. Now you hired 7 different people to do a google search for you . :)

like image 27
Vanchinathan Chandrasekaran Avatar answered Oct 01 '22 09:10

Vanchinathan Chandrasekaran


To be precise, StringBuilder adding all strings is O(N) while adding String's is O(N^2). Checking the source code, this is internally achieved by keeping a mutable array of chars. StringBuilder uses the array length duplication technique to achieve ammortized O(N^2) performance, at the cost of potentially doubling the required memory. You can call trimToSize at the end to solve this, but usually StringBuilder objects are only used temporarily. You can further improve performance by providing a good starting guess at the final string size.

like image 39
mahogny Avatar answered Oct 01 '22 09:10

mahogny


Efficiency.

Each time you concatenate strings, a new string will be created. For example:

String out = "a" + "b" + "c";

This creates a new, temporary string, copies "a" and "b" into it to result in "ab". Then it creates another new, temporary string, copies "ab" and "c" into it, to result in "abc". This result is then assigned to out.

The result is a Schlemiel the Painter's algorithm of O(n²) (quadratic) time complexity.

StringBuilder, on the other hand, lets you append strings in-place, resizing the output string as necessary.

like image 22
Thomas Avatar answered Oct 04 '22 09:10

Thomas


Java has String, StringBuffer and StringBuilder:

  • String : Its immutable

  • StringBuffer : Its Mutable and ThreadSafe

  • StringBuilder : Its Mutable but Not ThreadSafe, introduced in Java 1.5

String eg:

public class T1 {

    public static void main(String[] args){

        String s = "Hello";

        for (int i=0;i<10;i++) {

            s = s+"a";
            System.out.println(s);
        }
    }
}

}

output: 10 Different Strings will be created instead of just 1 String.

Helloa
Helloaa
Helloaaa
Helloaaaa
Helloaaaaa
Helloaaaaaa
Helloaaaaaaa
Helloaaaaaaaa 
Helloaaaaaaaaa 
Helloaaaaaaaaaa

StringBuilder eg : Only 1 StringBuilder object will be created.

public class T1 {

    public static void main(String[] args){

        StringBuilder s = new StringBuilder("Hello");

        for (int i=0;i<10;i++) {    
            s.append("a");
            System.out.println(s);
        }
    }
}
like image 20
Kumar Vivek Mitra Avatar answered Oct 01 '22 09:10

Kumar Vivek Mitra