String, StringBuffer, and StringBuilder

后端 未结 11 1404
谎友^
谎友^ 2020-11-22 13:52

Please tell me a real time situation to compare String, StringBuffer, and StringBuilder?

相关标签:
11条回答
  • 2020-11-22 14:20

    String

    The String class represents character strings. All string literals in Java program, such as "abc" are implemented as instances of this class.

    String objects are immutable once they are created we can't change. (Strings are constants)

    • If a String is created using constructor or method then those strings will be stored in Heap Memory as well as SringConstantPool. But before saving in pool it invokes intern() method to check object availability with same content in pool using equals method. If String-copy is available in the Pool then returns the reference. Otherwise, String object is added to the pool and returns the reference.

      • The Java language provides special support for the string concatenation operator (+), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.

      String heapSCP = new String("Yash");
      heapSCP.concat(".");
      heapSCP = heapSCP + "M";
      heapSCP = heapSCP + 777;
      
      // For Example: String Source Code 
      public String concat(String str) {
          int otherLen = str.length();
          if (otherLen == 0) {
              return this;
          }
          int len = value.length;
          char buf[] = Arrays.copyOf(value, len + otherLen);
          str.getChars(buf, len);
          return new String(buf, true);
      }
      
    • String literals are stored in StringConstantPool.

      String onlyPool = "Yash";
      

    StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's. StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.

    • StringBuffer and StringBuilder data can only be created using new operator. So, they get stored in Heap memory.

    • Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

      StringBuffer threadSafe = new StringBuffer("Yash");
      threadSafe.append(".M");
      threadSafe.toString();
      
      StringBuilder nonSync = new StringBuilder("Yash");
      nonSync.append(".M");
      nonSync.toString();
      
    • StringBuffer and StringBuilder are having a Special methods like., replace(int start, int end, String str) and reverse().

      NOTE: StringBuffer and SringBuilder are mutable as they provides the implementation of Appendable Interface.


    When to use which one.

    • If a you are not going to change the value every time then its better to Use String Class. As part of Generics if you want to Sort Comparable<T> or compare a values then go for String Class.

      //ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable
      Set<StringBuffer> set = new TreeSet<StringBuffer>();
      set.add( threadSafe );
      System.out.println("Set : "+ set);
      
    • If you are going to modify the value every time the go for StringBuilder which is faster than StringBuffer. If multiple threads are modifying the value the go for StringBuffer.

    0 讨论(0)
  • 2020-11-22 14:22

    Also, StringBuffer is thread-safe, which StringBuilder is not.

    So in a real-time situation when different threads are accessing it, StringBuilder could have an undeterministic result.

    0 讨论(0)
  • 2020-11-22 14:23
    • You use String when an immutable structure is appropriate; obtaining a new character sequence from a String may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated).
    • You use StringBuilder when you need to create a mutable character sequence, usually to concatenate several character sequences together.
    • You use StringBuffer in the same circumstances you would use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).

    See an example here.

    0 讨论(0)
  • 2020-11-22 14:25

    Do you mean, for concatenation?

    Real world example: You want to create a new string out of many others.

    For instance to send a message:

    String

    String s = "Dear " + user.name + "<br>" + 
    " I saw your profile and got interested in you.<br>" +
    " I'm  " + user.age + "yrs. old too"
    

    StringBuilder

    String s = new StringBuilder().append.("Dear ").append( user.name ).append( "<br>" ) 
              .append(" I saw your profile and got interested in you.<br>") 
              .append(" I'm  " ).append( user.age ).append( "yrs. old too")
              .toString()
    

    Or

    String s = new StringBuilder(100).appe..... etc. ...
    // The difference is a size of 100 will be allocated upfront as  fuzzy lollipop points out.
    

    StringBuffer ( the syntax is exactly as with StringBuilder, the effects differ )

    About

    StringBuffer vs. StringBuilder

    The former is synchonized and later is not.

    So, if you invoke it several times in a single thread ( which is 90% of the cases ), StringBuilder will run much faster because it won't stop to see if it owns the thread lock.

    So, it is recommendable to use StringBuilder ( unless of course you have more than one thread accessing to it at the same time, which is rare )

    String concatenation ( using the + operator ) may be optimized by the compiler to use StringBuilder underneath, so, it not longer something to worry about, in the elder days of Java, this was something that everyone says should be avoided at all cost, because every concatenation created a new String object. Modern compilers don't do this anymore, but still it is a good practice to use StringBuilder instead just in case you use an "old" compiler.

    edit

    Just for who is curious, this is what the compiler does for this class:

    class StringConcatenation {
        int x;
        String literal = "Value is" + x;
        String builder = new StringBuilder().append("Value is").append(x).toString();
    }
    

    javap -c StringConcatenation

    Compiled from "StringConcatenation.java"
    class StringConcatenation extends java.lang.Object{
    int x;
    
    java.lang.String literal;
    
    java.lang.String builder;
    
    StringConcatenation();
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   aload_0
       5:   new #2; //class java/lang/StringBuilder
       8:   dup
       9:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
       12:  ldc #4; //String Value is
       14:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
       17:  aload_0
       18:  getfield    #6; //Field x:I
       21:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
       24:  invokevirtual   #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
       27:  putfield    #9; //Field literal:Ljava/lang/String;
       30:  aload_0
       31:  new #2; //class java/lang/StringBuilder
       34:  dup
       35:  invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
       38:  ldc #4; //String Value is
       40:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
       43:  aload_0
       44:  getfield    #6; //Field x:I
       47:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
       50:  invokevirtual   #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
       53:  putfield    #10; //Field builder:Ljava/lang/String;
       56:  return
    
    }
    

    Lines numbered 5 - 27 are for the String named "literal"

    Lines numbered 31-53 are for the String named "builder"

    Ther's no difference, exactly the same code is executed for both strings.

    0 讨论(0)
  • 2020-11-22 14:28

    Note that if you are using Java 5 or newer, you should use StringBuilder instead of StringBuffer. From the API documentation:

    As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

    In practice, you will almost never use this from multiple threads at the same time, so the synchronization that StringBuffer does is almost always unnecessary overhead.

    0 讨论(0)
提交回复
热议问题