Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In programming, particularly when dealing with complex data structures like arrays or objects, understanding the concepts of shallow copy and deep copy is crucial. These copying mechanisms dictate how data is replicated and manipulated, affecting both performance and behavior in your applications.
A shallow copy duplicates an object’s top-level properties but does not recursively copy nested objects. This means that while the outer object is a new instance, its nested objects are still references to the same instances as the original. On the other hand, a deep copy creates a complete clone of the entire object, including all nested objects, ensuring that the new object is entirely independent of the original. In this blog, we will delve into the fundamental differences between shallow and deep copies.
Shallow copy
A shallow copy is mainly a reference variable that stores the address of the object it is copied from. We are creating a new object with the same value as that of the original object. But if we change the values in this object, it will be affected in the original object also. So both objects share the same memory locations. Let's understand this with an example.
If we consider an object obj1 and store a name-value, say ‘Rajveer’ in it. Now we create another object name obj2 and copy obj1 into it. So in shallow copy, both the objects share the same memory allocation, and hence if we change the value of obj2, then the value of obj1 will also be changed.
It is making a copy of the reference of obj1 into obj2. It is pointing both obj1 and obj2 to the same memory locations. So when the value of one is changed, the other is changed automatically.
Now lets understand this using a code in javascript:
Implementation:
C++
Java
Python
Javascript
C++
#include <iostream> #include <cstring>
class Developer { public: std::string name; int age;
Developer(const std::string& name, int age) : name(name), age(age) {}
// Copy assignment operator for shallow copy Developer& operator=(const Developer& other) { if (this == &other) return *this; name = other.name; age = other.age; return *this; } };
So we can clearly see that when we changed develop2 , values of develop1 also changed.
Deep copy
Unlike shallow copy, deep copy copies all the fields and the memory allocated to it. Since it allocates different memory, it helps to create copied or cloned objects without worries of changing the old object. Let us understand this with examples.
If we consider an obj1 and store name and age in it say “Salman” ,“50”.Then we create a new obj2 and can copy obj1 into it. So in deep copying, when we change the value of obj2, there will be no changes in the value of obj1.
It is copying all values of obj1 and then assigning different memory locations to obj2. Hence if values of obj1 are changed or obj1 deletes, then there will be no changes in obj2.
Now let us understand this using a code in javascript.
Implementation:
C++
Java
Python
Javascript
C++
#include <iostream> #include <string>
class Developer { public: std::string name; int age;
Here we can clearly see that firstName didn't change while the city changed. This is because the first name is a primitive value while address is reference value.Both of these are referenced to different object by addressed to similar address.
object.assign() method
Object.assign() method is similar to spread syntax. Both of these perform shallow copying. Example for object.assign() method copying.
Implementation:
Javascript
Javascript
let person = { firstName: 'raj', lastName: 'arora', address: { city: 'delhi', state: 'india', } };
Different Scenarios Where Deep and Shallow Copies Are Similar
Here are some scenarios where shallow and deep copies can exhibit similar behavior or outcomes, despite their fundamental differences:
1. Simple Data Structures
Scenario: When copying simple data structures that don’t contain nested objects or complex references.
Example: Copying a list or an array of primitive values (e.g., integers, strings).
Shallow Copy: Creates a new list or array, but since there are no nested objects, the result is effectively the same as a deep copy.
Deep Copy: Also results in a new list or array with the same primitive values. No difference from shallow copy in this case.
Explanation: In cases where the data structure is flat and consists solely of primitive values, both shallow and deep copies result in identical outcomes, as there are no nested objects or references to consider.
2. Immutable Objects
Scenario: When working with immutable objects where the object's state cannot be modified.
Example: Strings or tuples in Python, or String objects in Java.
Shallow Copy: Creates a new reference to the same immutable object.
Deep Copy: Also results in a new reference to the same immutable object, as immutable objects cannot be modified.
Explanation: Since immutable objects cannot be changed once created, both shallow and deep copies result in equivalent outcomes because the object's content remains the same.
3. Simple Object with Non-Nested Properties
Scenario: When copying objects that contain only non-nested properties.
Example: An object with only primitive data types as properties.
Shallow Copy: Copies the object with all primitive properties, resulting in a new object that is functionally identical to the original.
Deep Copy: Also copies the primitive properties, leading to the same result as a shallow copy.
Explanation: When an object doesn’t contain any nested structures or references, both shallow and deep copies behave similarly, as they both effectively create a new object with the same values.
4. Unchanged Nested Structures
Scenario: When copying objects with nested structures where the nested objects themselves are not modified after copying.
Example: A complex object is copied, but neither the original nor the copied object modifies the nested structures.
Shallow Copy: Copies the top-level structure, and since nested structures are not altered, the outcome is similar to a deep copy.
Deep Copy: Results in a new object with new instances of nested structures. Since no modifications are made, both copies behave similarly.
Explanation: If no modifications are made to the nested structures after copying, the differences between shallow and deep copies are not apparent in terms of the object's behavior.
5. Read-Only Operations
Scenario: When the copied object is only used for read-only operations and is not modified.
Example: Copying an object to perform read operations without changing its state.
Shallow Copy: Provides a new reference to the same data for read-only purposes.
Deep Copy: Also provides a new reference to the same data for read-only purposes, with no observable difference.
Explanation: If the copied object is used only for reading and not for modifying, both shallow and deep copies can be functionally equivalent because no changes to nested structures are made.
Python’s copy module provides both shallow (copy.copy()) and deep copies (copy.deepcopy()) depending on the function used.
Is NumPy copy a deepcopy?
NumPy's copy() function performs a shallow copy; for deep copies, nested arrays require additional handling.
Is clone() a deep copy?
In Java, clone() performs a shallow copy by default; deep copying requires explicit implementation.
What is a reference object in javascript?
In javascript, the object reference is information on how to find that object.it is the reference to that object to get to the memory.
What is an object in javascript?
Objects in javascript are also variable but they store many values together. To declare variables we use the let key while for objects we use the const key. for example: Const book = {name;”secret” , author:”Xyz” , price:”rs.500”};
What is the use of object.create() method in javascript?
Object.create() method is used to create a new object using the prototype of an existing object.for example: Const a=object.create(x);
Conclusion
In this blog, we have discussed about shallow copy and deep copy. We also learned the difference between shallow copy and deep copy. Also we learned a few coping mechanisms to overcome shallow copy using javascript language. We hope that this blog has helped you enhance your knowledge regarding program to convert pascal case string to snake case string and if you would like to learn more, check out our articles on javascript. Do upvote our blog to help other ninjas grow. Happy Coding!”