Home  >  Article  >  Java  >  Analysis of the difference between StringBuffer and String in JAVA

Analysis of the difference between StringBuffer and String in JAVA

高洛峰
高洛峰Original
2017-01-22 09:36:141424browse

I saw this explanation is good, so I will turn to it

There are three classes in java that are responsible for character operations.

1.Character operates on a single character,

2.String operates on a string of characters, an immutable class.

3.StringBuffer also operates on a string of characters and is a variable class.

String:
It is an object, not a primitive type.
It is an immutable object. Once it is created, its value cannot be modified.
Any modifications to the existing String object are all new Create a new object and save the new value in it.
String is a final class, that is, it cannot be inherited.

StringBuffer:
is a mutable object, when it is modified The object will not be re-created like String
It can only be created through the constructor,
StringBuffer sb = new StringBuffer();
Note: It cannot be assigned a value through the assignment symbol.
sb = "welcome to here!";//error
After the object is created, memory space will be allocated in the memory and a null will be initially saved. When assigning a value to StringBuffer, you can use its append() method.
sb.append("hello");

StringBuffer is more efficient than String in string connection operations:

String str = new String("welcome to ");
str += "here";
The processing steps are actually to create a StringBuffer, then call append(), and finally
Convert StringBuffer toSting();
In this case, the String connection operation is There are some additional operations than StringBuffer, but of course the efficiency is compromised.

And because the String object is an immutable object, a new object will be re-created every time Sting is operated to save the new value.
This way The original object is useless and will be garbage collected. This will also affect performance.

Look at the following code:
Repeatedly add 26 English letters 5000 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, and the results obtained are not necessarily the same every time, usually around 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);

The result is 16 and sometimes 0
So the conclusion is obvious, StringBuffer is almost tens of thousands of times faster than String. Of course this data is not very accurate. Because when the number of cycles is 100,000, the difference is even greater. If you don’t believe me, try


If you still can’t understand:

1) The difference between String’s union + method and StringBuff’s append method:

# When ##String's + operator performs string operations, it first converts the current string object to the StringBuff type, calls its append method, and finally converts the generated StringBuff object into a String type string through its toString method. So its efficiency is lower.

But in terms of readability, String’s connection operator is still better.

2) StringBuff is thread-safe

String is thread-unsafe

3) String is a string object that cannot be modified, but StringBuff can be modified.

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(“源文件不存在”);
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(“文件拷贝异常:= ” + e.getMessage());
}
return flag;
}

For more articles related to the analysis of the difference between StringBuffer and String in JAVA, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn