Java 'Prototype' pattern - new vs clone vs class.newInstance

Guillaume picture Guillaume · Mar 11, 2010 · Viewed 6.9k times · Source

In my project there are some 'Prototype' factories that create instances by cloning a final private instance.

The author of those factories says that this pattern provides better performance than calling 'new' operator.

Using google to get some clues about that, I did not found anything relevant. Here is a small excerpt found in a javdoc from an unknown project

Sadly, clone() is rather slower than calling new. However it is a lot faster than calling java.lang.Class.newInstance(), and somewhat faster than rolling our own "cloner" method.

For me it's looking like an old best practice of the java 1.1 time. Does someone know more about this ? Is this a good practice to use that with 'modern' jvm ?

Answer

Mark Renouf picture Mark Renouf · Mar 11, 2010

Absolutely, this type of practice is completely obsolete. The Java virtual machine has improved drastically since then. Object creation is extremely cheap. Another related practice, Object Pooling, is also obsolete because the cost of Object creation and cleanup is so much more efficient now. For some cases it might be useful (Jon Skeet gives some good examples here), but in no way should it be part of a base framework library such as this.

I would suggest finding some new libraries and/or a new project to work on ;-)

Check out this class article Java Urban Performance Legends for some more insight.