String,StringBuffer,StringBuilder
用String,StringBuffer,StringBuilder测试一下速度,发现在Netbeans,Jcreator里执行结果有一定的差异StringBuffer应该是线程安全的,带有Sychronized的,而StringBuilder是以牺牲线程安全为代价的,在单线程情况下
应该会比StringBuffer来得快,在Netbeans得到了想要的结果.而在Jcreator里却是StringBuffer来得快一些..
这是为什么???
下附代码和结果:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package comparestrings;
//import java.util.*;
/**
*
* @author lynn
*/
public class CompareStrings {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String str = "abcdefghijklmnopqrstuvwxyz";
StringBuffer strBuffer = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
StringBuilder strBuilder = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
long time1= System.currentTimeMillis() ;
for(int i= 0 ;i<10000;i++)
str = str+"abcdefghijklmnopqrstuvwxyz";
long time2= System.currentTimeMillis() ;
long t1 = time2 - time1;
time1= System.currentTimeMillis() ;
for(int i= 0 ;i<10000;i++)
strBuffer.append("abcdefghijklmnopqrstuvwxyz");
time2= System.currentTimeMillis() ;
long t2 = time2 - time1;
time1= System.currentTimeMillis() ;
for(int i= 0 ;i<10000;i++)
strBuilder.append("abcdefghijklmnopqrstuvwxyz");
time2= System.currentTimeMillis() ;
long t3 = time2 - time1;
// System.out.println(str);
System.out.println("use time: "+t1 +" \n\n**********************************");
//System.out.println(strBuffer.toString());
System.out.println("use time: "+t2 +" \n\n**********************************");
//System.out.println(strBuilder.toString());
System.out.println("use time: "+t3 );
}
}
NetBeans运行结果:
run:
use time: 50953
**********************************
use time: 16
**********************************
use time: 0
Jcreator的运行结果: