The difference between String and StringBuilder in Java

  • 2020-04-01 01:43:15
  • OfStack

Believe everyone knows the difference between the String and StringBuffer has well, but still there will be many comrades working principle of the two classes have some unclear place, today I am here to give you the concept review, by the way leads to J2SE 5.0 brings a new character inside operation of class - the StringBuilder (don't throw me busy bricks, I still awake, I'm not C #, Java has StringBuilder class). So what's the difference between this StringBuilder and StringBuffer and the String class that we first encountered? Which one should we use in different situations? I would like to talk about my views on these categories, and I hope you can give us some Suggestions. Everyone has mistakes, and it is a good opportunity to learn while making mistakes.

      Briefly, the main performance difference between the String and StringBuffer types is that strings are immutable objects (why? Ask the Java designers why String isn't a native type. So when every time to change the type String is equal to generate a new String object, then the pointer to a new String object, so often it is best not to change the contents of the String with a String, because every time generated objects will have an effect on system performance, especially when memory without much reference object, the JVM GC will start to work, that is will be a rather slow speed. Here's a bad example:

String S1 = "ABC";
For(int I = 0; I < 10000; I ++) // For multiple calls to the simulation program
{
S1 + = "def";
S1 = "ABC";
}

      If that's the case, by the end of the for loop, if the objects in memory haven't been cleaned up by GC, there's over 20,000 of them in memory, which is an amazing number, and if this is a system that a lot of people use, that's not a lot, so you have to be careful.

      This is not the case with the StringBuffer class, where each time the result operates on the StringBuffer object itself, rather than generating a new object and changing the object reference. So we recommend using stringbuffers in general, especially when string objects change frequently. In some special cases, String object String splicing is actually interpreted by the JVM as a StringBuffer object splicing, so the String object is not slower than the StringBuffer object at these times, and in particular, the String object generation, String efficiency is much faster than the StringBuffer:

String S1 = "This is only a" + "simple" + "test";
StringBuffer Sb = new StringBuilder(" This is only a "). Append (" simple "). Append (" test ");

      You'll be surprised to find that the String S1 object is generated at such a fast rate that StringBuffer has no advantage in speed at all. This is actually a trick of the JVM, in the JVM's eyes, this

String S1 = "This is only a" + "simple" + "test"; String S1 = "This is only a simple test"; So of course it doesn't take much time. But the important thing to note here is that if your String comes from another String object, it's not as fast, like:

String S2 = "This is only a";
String S3 = "simple";
String S4 = "test";
String S1 = S2 +S3 + S4;

      At this point, the JVM will behave in the original way, and the generation of S1 objects will not be as fast as before. Later, we can do a test to verify it.

      This leads us to the first step: in most cases StringBuffer > The String

      And how does StringBuilder compare to them? For a brief introduction, StringBuilder is a new class added in JDK5.0 that differs from StringBuffer (source JavaWorld) :

      Java.lang.StringBuffer thread-safe variable character sequences. A String buffer that is similar to a String, but cannot be modified. String buffers can be used safely for multiple threads. These methods can be synchronized as necessary, so all operations on any given instance appear to occur in a serial order, in the order in which each of the involved threads makes method calls.

      Each string buffer has a certain capacity. There is no need to allocate a new internal buffer array as long as the string buffer contains a sequence of characters of length that does not exceed this capacity. This capacity is automatically increased if the internal buffer overflows. Starting with JDK 5.0, a single thread-used equivalence class, StringBuilder, has been added to the class. The StringBuilder class should generally be preferred over this class because it supports all the same operations, but is faster because it does not perform synchronization.

      However, it is not safe to use an instance of StringBuilder for multiple threads. If such synchronization is required, StringBuffer is recommended.

      Now that you can see the difference, let's do one more general derivation:

      In most cases StringBuilder > StringBuffer

      Therefore, according to the transfer theorem of this inequality, in most cases StringBuilder > StringBuffer > String (the higher the number of operations, the more stable).

 

Get System time long start = system.currenttimemillis (); Long end = System. CurrentTimeMillis (); Then you know how many milliseconds you are running.


import javax.swing.JOptionPane;
public class T1{
    public static void main(String args[]){
        String str;
        String str2;
        int i;
        StringBuffer sb=new StringBuffer();
        str=JOptionPane.showInputDialog(null," Enter a string ");
        for(i=0;i<str.length()/2;i++)
            if(str.charAt(i)!=str.charAt(str.length()-i-1))
                break;
        if(i>=str.length()/2)
            JOptionPane.showMessageDialog(null," It's a palindrome ");
        else 
            JOptionPane.showMessageDialog(null," Not a palindrome string ");

        

    }

}

Ignore either alphanumeric or numeric characters to determine palindrome strings

import javax.swing.JOptionPane;
 public class T2{
     public static void main(String args[]){
         String str;
         String str2;
         int i;
         StringBuffer sb=new StringBuffer();
         str=JOptionPane.showInputDialog(null," Enter a string ");
         for(i=0;i<str.length();i++)
         {
             if(Character.isLetterOrDigit(str.charAt(i)))
                 sb.append(str.charAt(i));
         }
         str=sb.toString();
         str2=sb.reverse().toString();
         /*
         for(i=0;i<str.length()/2;i++)
             if(str.charAt(i)!=str.charAt(str.length()-i-1))
                 break;

         */
         if(str.equals(str2))
             JOptionPane.showMessageDialog(null," It's a palindrome ");
         else 
             JOptionPane.showMessageDialog(null," Not a palindrome string ");

         

     }

 }


Related articles: