public class TestStringBuffereBuillder {
final static int NUM = 100000000;
public static void main(String[] args) {
//测试的次数
for (int j = 0; j < 5; j++) {
System.out.print(j+" ");
testString();
testStringBuffere();
testStringBuilder();
}
}
public static void testString(){
String string = "mmmmxxxxyy";
long startTime = System.currentTimeMillis();
for (int i = 0; i < NUM; i++) {
//String类中的方法,用于在String后连接字符串
string.concat("88");
//截取新的字符串
string = string.substring(0, 10);
}
long endTime = System.currentTimeMillis();
System.out.print((endTime - startTime) + "ms ");
}
public static void testStringBuffere(){
StringBuffer stringBuffer = new StringBuffer("mmmmxxxxyy");
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < NUM; i++) {
//StringBuffer与StringBuillder中的方法,末尾添加字符串与删除制定位置的字符串
stringBuffer.append("88");
stringBuffer = stringBuffer.delete(10, 12);
}
long endTime1 = System.currentTimeMillis();
System.out.print((endTime1 - startTime1) + "ms ");
}
public static void testStringBuilder(){
StringBuilder stringBuilder = new StringBuilder("mmmmxxxxyy");
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < NUM; i++) {
stringBuilder.append("88");
stringBuilder = stringBuilder.delete(10, 12);
}
long endTime1 = System.currentTimeMillis();
System.out.println((endTime1 - startTime1) + "ms");
}
}
输出结果