string,stringbuffer,stringbuilder 效率。stringbuilder > stringbuffer > string
测试用例代码如下。
package cui.yao.nan.optional;
import java.util.Random;
/**
* @Author: cuiyaonan2000@163.com
* @Description: todo
* @Date: Created at 2022-1-12 14:46
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Random random = new Random(1000);
long a = System.currentTimeMillis();
String a1 = new String("a");
for (int i = 0; i < 10000; i++) {
a1 += random.nextFloat();
}
long b = System.currentTimeMillis();
System.out.println("string:" + (b - a));
// System.out.println(a1);
long c = System.currentTimeMillis();
StringBuffer c1 = new StringBuffer("a");
for (int i = 0; i < 10000; i++) {
c1.append(random.nextFloat());
}
long d = System.currentTimeMillis();
System.out.println("stringbuffer:" + (d - c));
// System.out.println(c1);
long e = System.currentTimeMillis();
StringBuilder e1 = new StringBuilder("a");
for (int i = 0; i < 10000; i++) {
e1.append(random.nextFloat());
}
long f = System.currentTimeMillis();
System.out.println("stringbuild:" + (f - e));
// System.out.println(e1);
}
}
显示结果如下
string:1343
stringbuffer:16
stringbuild:0