DEV Community

Coder
Coder

Posted on • Originally published at itscoderslife.wordpress.com on

Deep copy and Shallow Copy

This is an important concept of computer science. You may have heard it very less in your day-to-day work life but your work will directly or indirectly relate to this one of the main concept of memory management. Let’s dive into this.

Here is scenario – Assume you have a team of 5 members. You have created a document on Google Drive and shared the link to the document with your team members.

Now how the doc is used / consumed is upto the members. Primarily there are two ways:

  1. One is : Using the online version directly to read/update or if someone updates you get the latest update directly. One can see the changes live.
  2. The other way is: Download a copy to your local system and use it as per your wish, manipulate it update it without altering the original copy which is on the cloud.

Thats it. If you know the difference between the 2 above,You got the concept! The first one is Shallow copy of the document and the second one is Deep copy of the document.

Now using this analogy let me explain you the memory management concepts of Objective-C and Swift.

  • strong : Members who have doc added to their own drive. Even if original is deleted the doc is not deleted. The reference link still points to the doc
  • weak : Members who have access to the doc will be informed upon deletion of the doc. Now the reference link will be invalid. It will point to nil.
  • assign : Members who have access to the doc will NOT be informed upon deletion of the doc. Now the reference link will be invalid. App crashes if the link is accessed.
  • copy : Members download copy of the doc to their own system. Does not effect if either of them are modified or deleted. Takes up additional memory unlike the above 3 which are referenced to same memory location. Mutable copy is when document is downloaded with RW permissions.

The 4 statements above may or maynot hold good for Google drive but only used to explain the concept.

Pros & Cons:

Shallow copy

  • Doc link which is stored in the cloud
  • Owner and admins is the strong reference
  • Non admins will have weak reference
  • Changes to the document will be notified to every member

Deep copy

  • Document downloaded to local system
  • Consumes additional storage
  • If some one changes in the cloud does not effect your local system
  • Whatever you change locally does not effect cloud version

I made up this analogy because I found it easier to link both the concepts for understanding. Let me know if you find this difficult or missing. Please share your comments below.

happyCoding();



Dam's DEV Profile

Top comments (0)