Performance of Cloning (either by Cloneable Interface or Copy Constructor) a object vs Creating a new object in Prototype Pattern

与世无争的帅哥 提交于 2021-02-04 08:12:59

问题


Recently, while learning about Design Patterns, I learnt that the Prototype Pattern is very useful and performance efficient in scenarios where huge number of Object creation is needed.

Prototype Pattern also minimizes the expense of too many object creations by making use of Cloneable interface or Copy Constructor in Prototype Pattern.

But, I would like to know how does cloning or copying an object more efficient than creating a new object. A JVM level explanation would be great.

Is this the only reason Prototype Pattern is made used?


回答1:


The prototype pattern isn't used for performance (although according to Ioannis' link, it has been used as a performance hack). It's used so you can create new objects from a (possibly changing) prototype.

Some method of "cloning" is needed so you don't have to care about the state of prototype. You can just call prototype.someMethodThatReturnsACopy() and the object is ready for use. You could use clone() or some other way to create that copy, even manually constructing one if you really want.




回答2:


It is interesting that you recently learned that Prototype Pattern is performant as that design pattern is outdated. You can check this stackoverflow question which is almost 10 years old




回答3:


Previous answers are correct in that the Prototype pattern is not a useful performance tool in Java.

The GoF book states on page 121,

Prototype is particularly useful with static languages like C++, where classes are not objects, and little or no type information is available at run-time. It's less important in languages like Smalltalk or Objective C that provide what amounts to a prototype (i.e., a class object) for creating instances of each class. This pattern is built into prototype-based languages like Self, in which all object creation happens by cloning a prototype.

A more modern prototype-based language is JavaScript. Some pros and cons are discussed in prototype based vs. class based inheritance.



来源:https://stackoverflow.com/questions/58231681/performance-of-cloning-either-by-cloneable-interface-or-copy-constructor-a-obj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!