tags:

views:

346

answers:

7

When we want to have new objects for some class, and if we already have one, should we use clone() or instantiate using new keyword?

Yes, clone() will have all the members copied as well, but I am curious for a case when this won't matter.

ClassType foo = new ClassType();
ClassType bar = new ClassType();  // here, will foo.clone() be better choice?

I need this in one of my current task as I am working with generic lists (List<T>), which get huge at times and are passed through a 'n' tiers before actually being used for UI.(they in between get converted to Array and back to list as well for serialization purpose). So, I was just thinking to better the performance.

+1  A: 

.clone is definitely slower.

zodeus
+6  A: 

Clone() will do a new anyhow, so why bother?

Calling Clone() will result in a new reference anyway and on top of that all members are copied, so it will definitely be slower.

Gerrie Schenck
+1  A: 

I imagine new, because clone will have to still new up the object in the background, plus the regular clone duties.

And as always, if in doubt, profile!

Mufasa
+1  A: 

clone must allocate a new object (i.e., it calls new somewhere), so it can't possibly perform better. In other words, new perforamance is a lower bound for clone performance.

zweiterlinde
+1  A: 

This would depend on how much work gets done in the constructor. Clone() would copy every member value from the first class to the second. Does your constructor do more, or less work than that? The answer to that should tell you.

Kevin Laity
+3  A: 

It sounds like you are doing premature optimisation. Profile, and you will usually be surprised where the time is going. I doubt it will be here, unless your "clone" is using serialization.

That said; ICloneable.Clone() is worth avoiding simply because it is poorly defined (deep vs shallow) and rarely supported. Behind the scenes, most Clone() implementations either just do a new(); // now copy properties, or they use serialization.

Marc Gravell
+2  A: 

Cloning is intended to produce an object identical (more or less - i.e. deep vs shallow - i.e. a minefield) to the original, a different purpose from new which merely instantiates an unrelated class instance.

Summary: They serve different purposes, they aren't interchangeable.

annakata
yes, that makes sense.
Kunal S