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 ?
Prototype design pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. Prototype pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs.
The Prototype pattern lets you clone a prototype instead of asking a factory method to make a new object.
Prototype is a creational design pattern that allows cloning objects, even complex ones, without coupling to their specific classes. All prototype classes should have a common interface that makes it possible to copy objects even if their concrete classes are unknown.
The classes participating to the Prototype Pattern are: Client – creates a new object by asking a prototype to clone itself. Prototype – declares an interface for cloning itself. ConcretePrototype – implements the operation for cloning itself.
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.
My tests with DecimalFormat (OpenJDK 8/Windows/JMH 1.19) shows completely opposite image:
Benchmark Mode Cnt Score Error Units
Format.everyTimeCreate avgt 10 9326.967 ± 199.511 us/op
Format.useClone avgt 10 5102.397 ± 72.993 us/op
Format.useGlobalWithTL avgt 10 4605.604 ± 59.000 us/op
Looks like it is not so simple to answer what is perform better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With