Clone和new哪個更快呢,這個問題的答案不是一定的,要根據實際情況決定:
情況一:對象簡單,這個時候new更快,測試代碼如下:
public Object clone(){
Object obj = null ;
try{
obj = super.clone();
}catch(Exception e){
}
return obj;
}
}
public class CloneVsNew {
static void cloneTest(int time){
TestObj obj=new TestObj();
for(int i=0;i<time;i++){
obj.clone();
}
}
static void newTest(int time) {
TestObj obj=new TestObj();
for(int i=0;i<time;i++){
obj=new TestObj();
}
}
/** *//**
* @param args
*/
public static void main(String[] args) {
long start;
long stop;
int times=1000000;
System.gc();
start=System.currentTimeMillis();
newTest(times);
stop=System.currentTimeMillis();
System.out.println("newTest Time:"+(stop-start));
System.gc();
start=System.currentTimeMillis();
cloneTest(times);
stop=System.currentTimeMillis();
System.out.println("cloneTest Time:"+(stop-start));
}
}
情況二:對象複雜,例如一個包括集合類的類的對象。而且這個對象的Clone使用的淺拷貝。(其實快主要是快在這個地方)
不用例子了,淺拷貝只是引用的複製,肯定比複製快。
還有一些其它的情況,但總體來說,隨着對象的複雜,clone越來越快,new越來越慢。不過在使用clone的時候
一定要想清楚再用,淺拷貝使用不當會出現很多問題。