Shallow Copy
- A shallow copy creates a new object, but inserts references into it to the objects found in the original.
- Changes made to a shallow copy of an object can reflect in the original object if the changes are made to a mutable object contained within the shallow copy.
Example:
import copy
original_list = [1, 2, [3, 4]]
shallow_copy = copy.copy(original_list)
shallow_copy[2][0] = 'changed'
print("Original List:", original_list) # [1, 2, ['changed', 4]]
print("Shallow Copy:", shallow_copy) # [1, 2, ['changed', 4]]
Deep Copy
- A deep copy creates a new object and recursively adds the copies of nested objects present in the original.
- Changes made to a deep copy of an object do not affect the original object.
Example:
import copy
original_list = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original_list)
deep_copy[2][0] = 'changed'
print("Original List:", original_list) # [1, 2, [3, 4]]
print("Deep Copy:", deep_copy) # [1, 2, ['changed', 4]]
Shallow Copy vs Deep Copy in JavaScript
Shallow Copy
- A shallow copy copies an object’s properties into a new object. If the property value is a reference to an object, only the reference is copied.
Example:
let originalArray = [1, 2, [3, 4]];
let shallowCopy = originalArray.slice();
shallowCopy[2][0] = 'changed';
console.log("Original Array:", originalArray); // [1, 2, ['changed', 4]]
console.log("Shallow Copy:", shallowCopy); // [1, 2, ['changed', 4]]
Deep Copy
- A deep copy creates a new object and recursively copies all properties, ensuring that no references to the original objects are retained.
Example:
let originalArray = [1, 2, [3, 4]];
let deepCopy = JSON.parse(JSON.stringify(originalArray));
deepCopy[2][0] = 'changed';
console.log("Original Array:", originalArray); // [1, 2, [3, 4]]
console.log("Deep Copy:", deepCopy); // [1, 2, ['changed', 4]]
Key Points
- Shallow copies are faster but do not handle nested objects.
- Deep copies are slower but ensure complete independence from the original object.
Would you like a visual representation of these concepts?
Further Reading:
What is the difference between deep copy and shallow copy in JavaScript ? Interview Happy
Leave a Reply