Clone和new哪个更快呢,这个问题的答案不是一定的,要根据实际情况决定:
情况一:对象简单,这个时候new更快,测试代码如下:
class
TestObj
implements
Cloneable
{
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));
}
}
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的时候
一定要想清楚再用,浅拷贝使用不当会出现很多问题。