5

I understand what the difference between a shallow and deep copy are, but I really don't understand in what situations a shallow copy would be preferred.

If I'm not mistaken, shallow copy makes a new copy of the value types and simply copies the address of reference types so they are pointing to the same object, correct? Why would I ever want this effect?

David Torrey
  • 1,335
  • 3
  • 20
  • 43
  • 1
    Imagine that your type represents a smart pointer (in e.g. C++), or a list (in a functional language like Haskell). A deep copy is definitely not what you want in these cases. – Oliver Charlesworth Apr 13 '14 at 14:43

2 Answers2

3

In fact a shallow copy is the way with least effort, doing less. It is especially suited for immutable objects, where sharing is optimal.

An immutable object does not have an internal state, cannot be changed, only variables can be set to another value.

In java String and BigDecimal are immutable.

Immutable objects allow making better use of threads too.

For mutable classes you might be interested in copy-on-write data structures, where sharing happens till one variable is written to.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

I think one good example could help understanding the concept. Suppose you have a list of tuples. And you the list to a function to process something on. Creating some sub-lists from the original one could help in a function and this is not necessary to deep-copy all the tuples in the list. And you just need to copy those pointers (shallow-copy).

Hassan Ketabi
  • 2,924
  • 2
  • 22
  • 31