Java中连接字符串
方法:通过“+”操作符和StringBuffer.append()方法来连接字符串,并比较其性能
public class StringConcatenate {
public static void main(String[] args){
long staticTime = System.currentTimeMillis();
System.out.println(staticTime);
for (int i = 0; i < 5000; i++) {
String result = "this is"+"trsting the"+"difference"+"between"+"String"+"and"+"StringBuffer";
}
long endTime = System.currentTimeMillis();
System.out.println(endTime);
System.out.println("字符串连接"+"-使用+操作符:"+(endTime)+"ms");
long startTime1 = System.currentTimeMillis();
System.out.println(startTime1);
for (int i = 0; i < 5000; i++) {
StringBuffer result = new StringBuffer();
result.append("this is");
result.append("testing the");
result.append("difference");
result.append("between");
result.append("Sting");
result.append("and");
result.append("StringBuffer");
}
long endTime1 = System.currentTimeMillis();
System.out.println(endTime1);
System.out.println("字符串连接"+"-使用+操作符:"+(endTime)+"ms");
}
}
结果: