Foreword

In the previous section we explained the characteristics of strings. In addition to the string class, there are two other classes that we will often use, namely StringBuffer and StringBuilder. Because strings are immutable, every time we modify a string, such as by concat, trim, etc., a new string object is created. So how do we do without creating string garbage (a lot of temporary strings)? What about manipulating strings? The answer is to use StringBuffer and StringBuilder. StringBuffer is an old class, but StringBuilder was added in Java 5, and major improvements have been made in Enum, Generics, etc. and Autoboxing in Java.

 

StringBuffer VS StringBuilder

The main difference between String and StringBuffer is that String is immutable, while StringBuffer and StringBuilder are mutable, which means we can modify it when creating a StringBuffer object without creating any new objects. This mutable property makes StringBuffer become Ideal for working with strings in Java, this variability is more time-saving and consumes less resources. Of course we can convert StringBuffer to String by toString. These two classes are almost the same. They return the same result using a method with the same name. We can see the difference by looking at the Append method in the StringBuffer and StringBuilder source code:

 

 

   @Override
     public  synchronized StringBuffer append (String str) {
        toStringCache = null ;
         super .append (str);
         return  this ;
    }

 

 

    @Override
     public StringBuilder append (String str) {
         super .append (str);
         return  this ;
    }

 

Thread safety: StringBuffer methods are synchronous, which means that only one thread can call a method of a StringBuffer instance at a time. StringBuilder methods, on the other hand, are not synchronized, so multiple threads can call methods in the StringBuilder class without being blocked. So we conclude that StringBuffer is a thread-safe class, while StringBuilder is not. If we are dealing with an application that uses multiple threads, then using StringBuilder may be thread-unsafe.

Speed: StringBuffer is actually two to three times slower than StringBuilder. The reason behind this is StringBuffer synchronization, which allows only one object to execute on one object at a time, resulting in much slower code execution.

Both StringBuffer and StringBuilder have the same methods (except for the synchronized method declaration in the StringBuffer class). The following are common methods:

  • append()
  • insert()
  • replace()
  • delete()
  • reverse()

We use the above common methods through the following examples:

 

 

public  class Main {
     public  static  void main (String [] args) {
        StringBuffer sb = new StringBuffer ("Buffer no 1" );
        System.out.println (sb);

        sb.append ( " -and this is appended!" );
        System.out.println (sb);
        sb.insert ( 11, ", this is inserted" );
        System.out.println (sb);
        sb.replace ( 7, 9, "Number" );
        System.out.println (sb);
        sb.delete ( 7, 14 );
        System.out.println (sb);
        sb.reverse ();
        System.out.println (sb);
    }
}

 

 

Java_entry_series_[3]_StringBuilder,_StringBuffer_0.png

Next, let’s perform performance tests on String, StringBuffer, and StringBuilder.

 

 

  String concatString = "concatString" ;
        StringBuffer appendBuffer = new StringBuffer ("appendBuffer" );
        StringBuilder appendBuilder = new StringBuilder ("appendBuilder" );
         long timerStarted;

        timerStarted = System.currentTimeMillis ();
         for ( int i = 0; i <50000; i ++ ) {
            concatString + = "another string" ;
        }
        System.out.println ( "Time needed for 50000 String concatenations:" + (System.currentTimeMillis ()-timerStarted) + "ms" );

        timerStarted = System.currentTimeMillis ();
         for ( int i = 0; i <50000; i ++ ) {
            appendBuffer.append ( "another string" );
        }
        System.out.println ( "Time needed for 50000 StringBuffer appends:" + (System.currentTimeMillis ()-timerStarted) + "ms" );

        timerStarted = System.currentTimeMillis ();
         for ( int i = 0; i <50000; i ++ ) {
            appendBuilder.append ( "another string" );
        }
        System.out.println ( "Time needed for 50000 StringBuilder appends:" + (System.currentTimeMillis ()-timerStarted) + "ms");

 

 

Java_entry_series_[3]_StringBuilder,_StringBuffer_1.png

The printout above varies depending on the Java virtual machine. From the benchmark test above, we can still see that StringBuilder is the fastest in string operations, followed by StringBuffer, which is more than 1 times slower than StringBuilder, and finally String. The slowest. Using StringBuilder takes a series of times faster than normal String. So does it mean that we completely abandon the use of strings when operating on strings? Of course not, everything is not absolute, such as simple operations on strings, and there is not much performance loss when using strings directly.

String: Immutable (which means more memory consumption) and very slow when doing string operations, but thread-safe.

StringBuffer: Variable and memory efficient, and thread-safe. Compared to faster StringBuilders, their speed of decline is speed.

StringBuilder: Mutable and memory efficient, they are the fastest of string operations, but unfortunately they are not thread safe.

Summary

In this section, we compare the difference between StringBuffer and StringBuilder. It is a note to take. There is no difficulty in understanding. If we consider based on the above facts, we will always make the right choice!

 

Java entry series [1] string creation method

Java entry series [2] string features

Java entry series [3] stringbuilder string buffer

Java entry series [4] packaging class

Java entry series [5] inheritance abstract classes interfaceson

Java entry series [6] Principles of dynamic array

Java entry series [7] collection arraylist

Java entry series [8] principles of doubley linked list alogrithm

Java entry series [9] linkedlist source code analysis

Java entry series [10] Hash algorithm principle

Java entry series [11] Hashtable source code analysis

Java entry series [12] Hashcode and equals

Java entry series [13] Principles of the read-black tree algorithmn method

Java entry series [14] Hashmap source code ananlysis

 

Orignal link:https://www.cnblogs.com/CreateMyself/p/11437024.html