创建 com.rits.cloning.Cloner 昂贵吗?
Is creating a com.rits.cloning.Cloner expensive?
所有的例子都说它是线程安全的,并且有这样的例子:
Cloner cloner=new Cloner();
MyClass clone=cloner.deepClone(o);
在我的代码中,我就是这样做的:每次克隆时都创建一个新的。所以问题是:这个昂贵的对象是应该创建一次并重复使用还是正在制作一个新对象?
使用这个测试:
@Test
public void loadTestCloner() {
Calendar cal = GregorianCalendar.getInstance();
long timer = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Cloner c1 = new Cloner();
Calendar x = c1.deepClone(cal);
}
System.out.println("total time for new one each time: [" + (System.currentTimeMillis() - timer) + "]ms");
long timer2 = System.currentTimeMillis();
Cloner c2 = new Cloner();
for (int i = 0; i < 100000; i++) {
Calendar x = c2.deepClone(cal);
}
System.out.println("total time for reused one: [" + (System.currentTimeMillis() - timer2) + "]ms");
}
Calander 结果:
- 每次新的总时间:[644]ms
- 重复使用的总时间:[39]ms
并使用我们的复杂对象:
- 每次换新的总时间:[9585]ms
- 重复使用的总时间:[416]ms
并且仅使用 1 个对象并使用 "out of timer" 克隆器:
- 每次换新的总时间:[13]ms
- 重复使用的总时间:[0]ms
所以我得出的结论是,虽然时间不多,而且由于它是线程安全的,所以最好一次性完成并重复使用。
所有的例子都说它是线程安全的,并且有这样的例子:
Cloner cloner=new Cloner();
MyClass clone=cloner.deepClone(o);
在我的代码中,我就是这样做的:每次克隆时都创建一个新的。所以问题是:这个昂贵的对象是应该创建一次并重复使用还是正在制作一个新对象?
使用这个测试:
@Test
public void loadTestCloner() {
Calendar cal = GregorianCalendar.getInstance();
long timer = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Cloner c1 = new Cloner();
Calendar x = c1.deepClone(cal);
}
System.out.println("total time for new one each time: [" + (System.currentTimeMillis() - timer) + "]ms");
long timer2 = System.currentTimeMillis();
Cloner c2 = new Cloner();
for (int i = 0; i < 100000; i++) {
Calendar x = c2.deepClone(cal);
}
System.out.println("total time for reused one: [" + (System.currentTimeMillis() - timer2) + "]ms");
}
Calander 结果:
- 每次新的总时间:[644]ms
- 重复使用的总时间:[39]ms
并使用我们的复杂对象:
- 每次换新的总时间:[9585]ms
- 重复使用的总时间:[416]ms
并且仅使用 1 个对象并使用 "out of timer" 克隆器:
- 每次换新的总时间:[13]ms
- 重复使用的总时间:[0]ms
所以我得出的结论是,虽然时间不多,而且由于它是线程安全的,所以最好一次性完成并重复使用。