public class Test {
public static void directSetValue(int times){
BeTest test = new BeTest();
for(int i=0;i<times;++i){
test.setId(i);
test.setName("dsfs");
test.setName2("sdf");
test.setName3("et");
}
}
public static void createObject(int times){
for(int i=0;i<times;++i){
new BeTest(i,"dsfs","sdf","et");
}
}
public static void cloneObject(int times){
BeTest test = new BeTest(1,"dsfs","sdf","et");
for(int i=0;i<times;++i){
test.clone();
}
}
public static void main(String args[]){
int times=100000000;
long current=System.currentTimeMillis();
directSetValue(times);
long useTime = System.currentTimeMillis()-current;
current=System.currentTimeMillis();
createObject(times);
long useTime2 = System.currentTimeMillis()-current;
current=System.currentTimeMillis();
cloneObject(times);
long useTime3 = System.currentTimeMillis()-current;
System.err.println("复值方式构建对象:"+useTime+"\n直接创建对象:"+useTime2+
"\n克隆方式创建对象:"+useTime3);
}
}
class BeTest implements Cloneable{
private Integer id;
private String name;
private String name2;
private String name3;
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setName2(String name2) {
this.name2 = name2;
}
public void setName3(String name3) {
this.name3 = name3;
}
public BeTest() {
super();
}
public BeTest(Integer id, String name, String name2, String name3) {
super();
this.id = id;
this.name = name;
this.name2 = name2;
this.name3 = name3;
}
public Object clone(){
Object t=null;
try {
t= super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
}
结果显示:
复值方式构建对象:481
直接创建对象:361
克隆方式创建对象:651
总结:如果不考虑内存,直接创建对象,比通过对象池方式或克隆对象方式获取对象更加高效
网友评论