转:Clone和New哪个更快

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));
        
    }


}


情况二:对象复杂,例如一个包括集合类的类的对象。而且这个对象的Clone使用的浅拷贝。(其实快主要是快在这个地方)
不用例子了,浅拷贝只是引用的复制,肯定比复制快。

还有一些其它的情况,但总体来说,随着对象的复杂,clone越来越快,new越来越慢。不过在使用clone的时候
一定要想清楚再用,浅拷贝使用不当会出现很多问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值