Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a shallow copy desirable (instead of a deep copy)?

Can someone give an example of a situation where a shallow copy is needed?

Note that in some situations, shallow copy and deep copy are the same. This can happen when the object has no ownership over any of its subvariables; that is, all subvariables are aggregated. I'd like to see examples where the an object is composed from variables which it owns, and it still is desirable to copy them shallowly.

Remark: I don't care in which language the examples are given. I'm asking this question from a C++/Java/C# point of view, although I think copying is a language agnostic concept.

like image 396
Dimitri C. Avatar asked Jul 28 '10 08:07

Dimitri C.


People also ask

When would you use a shallow copy over a deep copy?

Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well. Shallow copy is faster. Deep copy is comparatively slower.

Why would you want a shallow copy?

Shallow copies are useful when you want to make copies of classes that share one large underlying data structure or set of data.

What is the difference between a shallow copy and a deep copy?

In Shallow copy, a copy of the original object is stored and only the reference address is finally copied. In Deep copy, the copy of the original object and the repetitive copies both are stored.

Where do we prefer deep and shallow copying while copying objects in Java?

Shallow copy is preferred if an object has only primitive fields. Deep copy is preferred if an object has references to other objects as fields. Shallow copy is fast and also less expensive. Deep copy is slow and very expensive.


2 Answers

When the owned variables are immutable types, a shallow copy is sufficient. A deep copy is possible, but would only result in additional memory use.

like image 187
Niels van der Rest Avatar answered Nov 15 '22 19:11

Niels van der Rest


One possible use case is when the composed objects can be derived from state information that is present in the shallow copy and you want, for instance, to serialize your object.

You can store the shallow copy and then rebuild the complete object from the state upon deserialization.

like image 21
Vinko Vrsalovic Avatar answered Nov 15 '22 20:11

Vinko Vrsalovic