Duplicate! What to choose Deep Copy or Shallow Copy?

Sakshi
2 min readMay 8, 2021

--

Deep Copy: As the name suggest, it copy everything. That’s it! Yes, It create and form a two completely separate objects in the memory. Works with value type for example Structure, Array, Dictionary, Set, String etc.

Let me take a example of Deep copy to understand what’s going on behind the seen:

So, what this code would print to the console? (Example of Deep copy)

// prints “Dr. Abc”

// prints “Neurologist”

// prints “Dr. Xyz”

// prints “Surgeon”

As we can see the above given code snippet, both the object created are independently making their own copies in the memory because the change in one object does not reflect to other one.

Shallow Copy: Here we do not copy everything, in-fact we copy a reference type. So that mean shallow copy works with reference type for example Class. Here two collection share the individual elements.

Note: every time we copy a reference type, a shallow copy is created by default until we explicitly specify that it should be copied deeply.

Memory friendly: Shallow copy are more memory friendly than Deep copy as shallow copy only copy its reference address rather than the whole values in it.

Speed: Deep copy is faster than shallow copy, also Deep copies are less prone to race conditions and suits well in multithreaded environment.

Now you can choose your objects wisely!

Thanks for reading!

--

--

Sakshi
Sakshi

No responses yet