克隆是否比构造函数/工厂方法提高了性能? [英] Does cloning provide a performance improvement over constructors/factory methods?

查看:96
本文介绍了克隆是否比构造函数/工厂方法提高了性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在维护一个较旧的Java代码库(jvm 1.4),该库似乎使用克隆作为对象实例化的替代方法,我猜测这是一种性能优化.这是一个人为的例子:

public class Foo {
  private SomeObject obj; // SomeObject implements Cloneable
  public Foo() {
    obj = new SomeObject();
    obj.setField1("abc"); // these fields will have the same value every time
    obj.setField2("def");
  }
  public void doStuff() {
    SomeObject newObj = obj.clone(); // clone it instead of using a factory method
    // do stuff with newObj
  }
}

尽管有一些关于过早优化的常见警告,但实际上在某些时候这是推荐使用的习惯用法吗?

解决方案

调用clone()而不是复制构造函数或工厂方法的一个原因是其他选项均不可用.

与实现复制构造函数或工厂方法以执行相同操作相比,

实施clone()来执行浅对象复制(涉及到深复制)是微不足道的.要实现clone(),一个类只需实现Cloneable接口,并使用调用super.clone()的方法覆盖方法clone(),该方法通常调用Object.clone(). Object.clone()将原始对象的每个属性复制到副本的相应属性中,从而创建浅表副本.

尽管实现clone()很简单,但是仍然容易忘记实现Cloneable.因此,使用clone()复制对象的潜在风险是,如果该对象的类确实忽略了实现Cloneable的情况,并且clone()直接或间接调用Object.clone(),它将抛出CloneNotSupportedException. /p>

请参见以下代码示例和先前的讨论 不良的设计 Cloneable界面.

I'm maintaing an older Java code base (jvm 1.4) that seems to use cloning as an alternative to object instantiation, I'm guessing as a performance optimization. Here's a contrived example:

public class Foo {
  private SomeObject obj; // SomeObject implements Cloneable
  public Foo() {
    obj = new SomeObject();
    obj.setField1("abc"); // these fields will have the same value every time
    obj.setField2("def");
  }
  public void doStuff() {
    SomeObject newObj = obj.clone(); // clone it instead of using a factory method
    // do stuff with newObj
  }
}

The usual caveats about premature optimization notwithstanding, was this actually a recommended idiom at some point?

解决方案

One reason to invoke clone() instead of the copy constructor or a factory method is that none of the other options may be available.

Implementing clone() to perform a shallow object copy (deep copy is more involved) is trivial compared to implementing a copy constructor or a factory method to perform the same operation. To implement clone(), a class need simply implement the Cloneable interface and override method clone() with one that invokes super.clone() which usually invokes Object.clone(). Object.clone() copies every property of the original object into the corresponding property of the duplicate, thus creating a shallow copy.

Though implementing clone() is straightforward, it is still easy to forget to implement Cloneable. Consequently, a potential risk of using clone() to duplicate an object is that if the class of that object does neglect to implement Cloneable and clone() invokes Object.clone() either directly or indirectly, it will throw CloneNotSupportedException.

See this code example and a previous discussion on the poor design of the Cloneable interface.

这篇关于克隆是否比构造函数/工厂方法提高了性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆