Shallow vs Deep Copy (with examples)

  • A shallow copy shares its children with the original
  • A deep copy has its own copies of the children
Car make: BMW engine: gearbox: Gearbox gears: 6 Engine cylinders: 12 Shallow copy of Car object Car make: BMW engine: gearbox:
Car make: BMW engine: gearbox: Gearbox gears: 6 Engine cylinders: 12 Deep copy of Car object Car make: BMW engine: gearbox: Gearbox gears: 6 Engine cylinders: 12

Arrays

The above example showed an object graph. Same story for arrays.

Shallow copy of array Person age: 30
Person age: 30 Deep copy of array Person age: 30

If there are no children?

Since the concept of deep vs shallow concerns treatment of children, it’s meaningless to talk about deep vs shallow copying of objects (or arrays) that doesn’t have any children. When creating a copy of an array of integers for example, the copy can be viewed as both shallow and deep.

What about pointerA = pointerB?

When you do pointerA = pointerB no object is copied (so it’s neither a deep nor a shallow copy). A pointer value is copied and you could argue that this is a shallow copy, since the object it points at is not copied.

Mixed copies

Mixed copies are part shallow, part deep. If you for instance make shallow copies of the children, then the original and the copy may share the same “grand children”. You could say that the copying is “one level deep”. Another type of mixed copy would be if you create copies of some children, while sharing others. If you for example have a reference to a singleton, or an immutable object it doesn’t make sense to clone these objects.

Comments

Be the first to comment!