Sunday, April 1, 2012

String, StringBuffer and StringBuilder


Mutability Difference:
String is immutable, if you try to alter their values, another object gets created, whereasStringBuffer and StringBuilder are mutable so they can change their values.
Thread-Safety Difference:
The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder.StringBuilder is more efficient than StringBuffer.
Situations:
  • If your string is not going to change use a string Class because a String object is immutable.
  • If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, use a StringBuilder is good enough.
  • If your string can change, and will be accessed from multiple threads, use a StringBufferbecause StringBuffer is synchronous so you have thread-safety.

        StringBuilder sb = new StringBuilder("ABC", 50);

        // Append three characters (D, E, and F) to the end of the StringBuilder.
        sb.Append(new char[] { 'D', 'E', 'F' });

        // Append a format string to the end of the StringBuilder.
        sb.AppendFormat("GHI{0}{1}", 'J', 'k');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

        // Insert a string at the beginning of the StringBuilder.
        sb.Insert(0, "Alphabet: ");

        // Replace all lowercase k's with uppercase K's.
        sb.Replace('k', 'K');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

1 comment:

  1. String is an immutable class while StringBuilder & StringBuffer are mutable classes. StringBuffer is synchronized while StringBuilder is not.

    Below link can be useful to find more differences between String, StringBuffer & StringBuilder

    Difference between String, StringBuffer and StringBuilder

    http://newtechnobuzzz.blogspot.com/2014/07/difference-between-string-stringbuffer.html

    ReplyDelete