The difference and efficiency comparison of String, StringBuffer and StringBuilder

String is immutable, StringBuffer, StringBuilder are mutable

String and StringBuffer are thread-safe, StringBuilder is thread-unsafe (the append operation of StringBuffer uses synchronized)

String object concatenation has the slowest efficiency. StringBuilder is used for string concatenation under single thread, and StrngBuffer is used for string concatenation under multi-threading.


Execution time comparison:

String s = "ja" + "va"

String s1="ja"; StringBuffer sb=new StringBuffer("va");
sb.append(s1);

String s1="ja"; 
String s2 = "va"; 
String s = s1 +s2
A string constant that can be determined at the compile stage, and there is no need to create a String or StringBuffer object. The "+" concatenation operation using the string constant directly is the most efficient. In terms of time, the append efficiency of ①<③
StringBuffer objects is higher than the "+" connection operation of two String objects. In terms of time ②<③
Generally speaking, the execution time is from fast to slow StringBuilder, StringBuffer, String

StringBuilder is recommended for non-multithreaded operations on string buffers


Efficiency comparison:

String str = "";
long beginTime = System.currentTimeMillis();

for (int i = 0; i < 999999; i++){
str = str + i;
}

long endTime = System.currentTimeMillis();

System.out.println("执行时间:" + (endTime - beginTime));

The running time is too long, and I directly terminated the program without waiting for the end of the program.

StringBuffer buffer = new StringBuffer("");
long beginTime = System.currentTimeMillis();
for (int i = 0; i < 999999; i++){
buffer.append(i);
}
long endTime = System.currentTimeMillis();
System.out.println("执行时间:" + (endTime - beginTime));

output:

Execution time: 250
StringBuilder builder = new StringBuilder("");
long beginTime = System.currentTimeMillis();
for (int i = 0; i < 99999; i++){
builder.append(i);
}
long endTime = System.currentTimeMillis();
System.out.println("执行时间:" + (endTime - beginTime));

输出:

执行时间:188

在数量级相对较小的时候,StringBuffer和StringBuilder的区别不大,只有当数量级相对较大的时候才能体会到他们两个之间的效率差别。

StringBuffer为了做到线程安全,牺牲一定的效率是必然的。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325700575&siteId=291194637