Details of the differences between String and StringBuffer in java

  • 2020-07-21 08:00:44
  • OfStack

Details of the differences between String and StringBuffer in java

String:

An object is not a primitive type.
Is an immutable object. Once 1 is created, its value cannot be changed.
Any modification to an existing String object is to recreate a new object and save the new value.
String is the final class, which cannot be inherited.

StringBuffer:

Is a mutable object that when modified does not recreate the object as String did
It can only be set up by a constructor,
StringBuffer sb = new StringBuffer();
Once the object is created, it allocates memory space in memory and initially saves 1 null. Assigns to it via its append method.
sb.append("hello");

StringBuffer is significantly more efficient than String in string concatenation:

The String object is immutable, and each operation on Sting creates a new object to hold the new value.
When an StringBuffer object is instantiated, only this one object is manipulated.

I have written a small example here to test the difference between String and StringBuffer in time and space usage.


public class Test {  
  public static void main(String args[]) {  
      
    String str = "abc";  
    StringBuffer sb = new StringBuffer("abc");  
    Runtime runtime = Runtime.getRuntime();  
    long start = System.currentTimeMillis();  
    long startFreememory = runtime.freeMemory();  
    for (int i = 0; i < 10000; i++) {  
      str += i;  
      // test StringBuffer Time to open the comments   
      //sb.append(i);  
    }  
    long endFreememory = runtime.freeMemory();  
    long end = System.currentTimeMillis();  
    System.out.println(" Operating time :" + (end - start) + "ms," + " Memory consumption :"  
        + (startFreememory - endFreememory)/1024 + "KB");  
  }  
}  

Test results:

Use String to add a string to the 1 string 10,000 times
Operation time :1872ms, memory consumption :1301KB

Use StringBuffer to add a string to the 1 string 10,000 times
Operation time :15ms, memory consumption :162KB

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: