pencilCake
pencilCake

Reputation: 53263

Is Memberwise cloning less expensive than creating a new object?

I was reading about Prototype creational design pattern and came across an information that points out the less expensiveness of cloning the object THAN creating a new one -via calling new operator.

Is this true and if yes, why is that?

Thanks

Upvotes: 0

Views: 271

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726839

Cloning does require creating a new object, so you are not going to save much on the creation portion of the initialization. However, you may save on other elements of initialization:

  • If an object requires populating collections, and the constructor takes an unknown number of elements, the cloning routine may be able to save on some processing by sizing the collection upfront.
  • If an object creates immutable objects in its constructor, the prototype may set references to its own objects directly into the resultant object. Since these referenced inner objects are immutable, it is OK to share them. This way your system would save on creating these dependent objects.

Upvotes: 2

Related Questions