Parsing the difference between StringBuffer and String in JAVA

  • 2020-04-01 03:00:18
  • OfStack

I see that's a good illustration, so I'm going to turn it around

There are three classes in Java that handle character manipulation.

1.Character is a single Character operation.

2.String operations on a String of characters, immutable class.

3.StringBuffer is a mutable class that also operates on a string of characters.

String:
      Is an object, not a primitive type.
      Is an immutable object whose value cannot be changed once it is created.
      Any modification to an existing String object is to recreate a new object and save the new value.
String is a final class, that is, it cannot be inherited.

StringBuffer:
      It's a mutable object that doesn't get re-created like a String when it's modified
      It can only be built by constructors,
      StringBuffer sb = new StringBuffer();
Note: it cannot be valued by an assignment symbol.
Sb = "welcome to here!" ; / / the error
After the object is created, memory space is allocated in memory and a null is initially stored. Assignments to a StringBuffer can be made using its append() method.
Sb. Append (" hello ");

A StringBuffer is more efficient than a String in String concatenation operations:

String STR = new String("welcome to ");
STR + = "here";
The processing step is actually by creating a StringBuffer, then calling append(), and finally
Then a StringBuffer toSting ();
In this way, String has a few more additional join operations than StringBuffer, which is of course less efficient.

And since the String object is an immutable object, each operation Sting will re-create a new object to save the new value.
This makes the original object useless and garbage collected, which also affects performance.

Take a look at the following code:
The 26 English letters were repeated 5,000 times,


        String tempstr = "abcdefghijklmnopqrstuvwxyz";
        int times = 5000;
        long lstart1 = System.currentTimeMillis();
        String str = "";
        for (int i = 0; i < times; i++) {
            str += tempstr;
        }
        long lend1 = System.currentTimeMillis();
        long time = (lend1 - lstart1);
        System.out.println(time);

Unfortunately, my computer is not a supercomputer, the results may not be the same every time the general is about 46687.
That's 46 seconds.
Let's look at the following code again

        String tempstr = "abcdefghijklmnopqrstuvwxyz";
        int times = 5000;
        long lstart2 = System.currentTimeMillis();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < times; i++) {
            sb.append(tempstr);
        }
        long lend2 = System.currentTimeMillis();
        long time2 = (lend2 - lstart2);
        System.out.println(time2);

You get 16 and sometimes you get 0
So it's pretty clear that a StringBuffer is almost ten thousand times faster than a String. Of course, this figure is not very accurate. Because the number of cycles is at 100,000, the difference is greater. Try it

If you still can't understand:

1) the difference between String's joint + method and StringBuff's append method:

When String's + operator performs String operations, it first converts the current String object to a StringBuff type, invokes its append method, and finally converts the generated StringBuff object to a String String through its toString method, so it is less efficient.

But in terms of readability, String still has a higher join operator.

2) StringBuff is thread safe

Strings are threads that are not safe

3) String is a non-modifiable String object, and a StringBuff is modifiable.


public static boolean fileCopy(String srcStr, String destStr) {
File srcFile = null;
File destFile = null;
Reader reader = null;
Writer writer = null;
boolean flag = false;
try {
srcFile = new File(srcStr);
if (!srcFile.exists()) {
System.out.println( "Source file does not exist" );
System.exit(0);
} else {
reader = new FileReader(srcFile);
}
destFile = new File(destStr);
writer = new FileWriter(destFile);
char[] buff = new char[1024];
int len;
String str =  "" ;
StringBuffer sbuff = new StringBuffer();
while ((len = reader.read(buff)) != -1) {
//        str += new String(buff, 0, len);
sbuff.append(new String(buff,0,len));
}
//      writer.write(str.toCharArray());
writer.write(sbuff.toString().toCharArray());
flag = true;
writer.flush();
reader.close();
writer.close();
} catch (IOException e) {
System.out.println( "File copy exception :=  "  + e.getMessage());
}
return flag;
}


Related articles: