Shallow Copy Vs Deep Copy

By | September 4, 2023

Shallow Copy

A shallow copy is a type of copy made by cloning or copying the original object, but it does not contain copies of objects nested within the original object. Instead, it creates a new copy that references the same nested objects as the original object.

Let’s understand with the following diagram:

Shallow Copy and Deep Copy
Fig 1- Shallow Copy

As we make the clone or copy of the object, the primitive values get copied as they are (present into the original object) into the copied object, but for the nested object within the original object, only references to the nested objects get copied. It means the copied object is pointing to the nested object within the original object, which is further pointing to the memory address of the employee object stored inside the Heap memory.

Problem in Shallow Copy

In the above example, we see that the nested object within the copied object is pointing to the memory address of the employee object within the original object. Indirectly, it is pointing to the memory address of the employee object stored within the heap memory.

Shallow Copy
Fig 2- Shallow Copy

The problem with this type of clone or copy is that if we modify our copied object, it will also modify our original object, as both of them point to the same memory address as the nested objects within the original object.

Deep Copy

A deep copy is the type of copy that creates independent copies of nested objects present within the original object. In other words, when we deep copy to make a copy of an object, the copied object contains all the primitive member variables along with the separate copies of nested objects within the original object.

Deep Copy
Fig 3- Deep Copy

Difference between Shallow Copy and Deep Copy

AspectShallow CopyDeep Copy
Copy DepthIt copies only top-level structure.It copies top-level as well as nested structure.
IndependenceIn shallow copy, nested objects are shared with the original object.In deep copy, nested objects are separate and independent from the original object.
EfficiencyShallow copy are faster and uses less memory.Deep copy are slower and uses more memory due to duplicate nested objects.
Use CaseIt is useful when we want shared references to the nested objects.Useful when complete isolation between copy object and original object is needed.
ExampleCaching, Referencing etc.Data Serialization, Persistence etc.

Leave a Reply

Your email address will not be published. Required fields are marked *