在java中对于生成新的对象,我们常常用new来创建对象,但是new看起来不是那么的快速,好像是个很费资源的操作,而clone看起来比new要好的多,那么事实真的如此吗?
耳听为虚,眼见为实,来程序对比一下:
首先建立一个测试类,对此类进行new和clone操作
public class Test1 implements Cloneable{
String str;
public Test1(String str){
this.str=str;
}
@Override
public Test1 clone() throws CloneNotSupportedException{
return (Test1)super.clone();
}
}
主程序启动测试:分别进行10000000次new和clone,查看所用时间:
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
long t1=System.currentTi