The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2002

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Is cloning more efficient than new operator?

Posted by Matt Gerrans on January 19, 2002 at 10:24 PM

Of course cloning is less efficient than the new operator, since it involves creating an object, plus running all the code to copy member data, plus casting (since clone returns Object not whatever derived object you are cloning).

If the behavior you require is what you get from new, then there is no need to clone. You use clone() to copy an existing object, so you only need this if the existing object has pertinent state information. The most common example of the use of clone() would be when you have a method that takes a reference to a mutable object and wants to fool with it, but doesn't want to modify it (accidentally, or otherwise); in that case, you'd want a copy of the object to work on.

The other thing is, if you are using clone(), then you, or whoever wrote the object, needs to implement the (misspelled) interface correctly, whereas using new doesn't require any extra work. Relying on Object.clone() would be kind of silly.

Finally, it would be pretty easy to write a program that times itself in the task of creating several million objects using both methods. I'll put my money on new. Any takers?




Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us