处理字符串的StringBuffer类和String类时间效率对比。主要用到了System.currentTimeMillis();、append(); 。
我的java学习日记,不是技术文档哦。-- gt.liu - 20160321
测试代码如下:
//对比StringBuffer和String 的执行效率
import java.util.*;
public class Demo032003{
public static void main(String [] args){
//为了明显地看出两者的执行效率,分别将26个字母相加1000次
String aaa = "abcdefghijklmnopqrstuvwxyz";
int count = 1000;//叠加次数
//String
long timestart1 = System.currentTimeMillis();
//System.out.println("timestart1 = " + timestart1 );//test currentTimeMillis();
String str1 = "";
for( int i = 0; i < count; i++ )
str1 += aaa;
long timeend1 = System.currentTimeMillis();
System.out.println( "time1 = " + (timeend1 - timestart1) + "ms" );
//StringBuffer
long timestart2 = System.currentTimeMillis();
StringBuffer str2 = new StringBuffer();
for( int i = 0; i < count; i++ )
str2.append(aaa);
long timeend2 = System.currentTimeMillis();
System.out.println( "time2 = " + (timeend2 - timestart2) + "ms" );
}
}