Shallow copy –– When we copy a new object from the old object, then this new object is also pointing towards the same memory reference of the old object. This lowers memory usage as well. Both new and old objects are accessing the same memory location.
For example, a shallow copy makes a copy of the reference to X into Y. So, both the X and Y point to the same memory location.
Deep copy–– Deep copy a new object with a new memory location. This memory location references to this new object and its contents. Since a new memory location is created, it increases memory usage.
For example, a deep copy makes a copy of all the members of X, creates a new memory location for Y and then assigns the copied members to Y. So, both are pointing to different memory locations.
Let’s take an example
Let me explain this by example.
Here is the result.[crayon-5f0d4c65a54a2872231525/]
In this example, we created a
car object and copy it into another object
duplicateCar using the shallow copy. Now, I changed the
duplicateCar object to
red, then our original
car object color also changes to
red color. This means that, we are losing the original data as well.
This is how shallow copy works. Here point to be noted that we are not creating two objects, it is only one object with two memory references. So, if we change the value of any object, it will reflect changes in other objects as well.
Sometimes, shallow copy becomes problematic, since we expect the changes only in the copied object, not the original ones. This may lead to an error without your knowledge.
A shallow copy of the object can be done using
We have made a copy of
obj. Let’s see if immutability exists:
In the code above, we changed the value of the property
objCopy object to
89 and when we log the modified
objCopy object in the console, the changes only apply to
The last line of code checks that the
obj object is still intact and hasn’t change. This implies that we have successfully created a copy of the source object without any references to it.
Let’s see how deep copy works. We will now create the same object by using the properties from the original
This is an example of deep copy. We are assigning each property of
car object to properties of
duplicateCar object. Now, if you change any property of
duplicateCar object, it won’t affect the original
Below is the complete example of creating object using deep copy.[crayon-5f0d4c65a54b2439890580/]
I commented on the second line and created
duplicateCar using properties assignments.
We also changed the color property of
duplicateCar object, and there is no change in the original
A deep copy of the object can be done using