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

}
情况一:对象简单,这个时候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的时候
一定要想清楚再用,浅拷贝使用不当会出现很多问题。
Clone与New性能对比
本文通过实验比较了Java中对象克隆(clone)与新建(new)实例的性能差异。结果显示,对于简单对象,new操作更快;而对于包含集合类等复杂对象,则clone表现更优,尤其是在使用浅拷贝的情况下。
747

被折叠的 条评论
为什么被折叠?



