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:
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.
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.
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.
Difference between Shallow Copy and Deep Copy
|Aspect||Shallow Copy||Deep Copy|
|Copy Depth||It copies only top-level structure.||It copies top-level as well as nested structure.|
|Independence||In shallow copy, nested objects are shared with the original object.||In deep copy, nested objects are separate and independent from the original object.|
|Efficiency||Shallow copy are faster and uses less memory.||Deep copy are slower and uses more memory due to duplicate nested objects.|
|Use Case||It is useful when we want shared references to the nested objects.||Useful when complete isolation between copy object and original object is needed.|
|Example||Caching, Referencing etc.||Data Serialization, Persistence etc.|