"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Shallow Copy vs Deep Copy – What Are They Really? - Examples with JavaScript and Python

Shallow Copy vs Deep Copy – What Are They Really? - Examples with JavaScript and Python

Published on 2024-08-31
Browse:130

Introduction

In the programming world, copying data is a common task. However, not all copies are created equal. Two terms that often appear are shallow copy and deep copy. Understanding the difference between them is crucial to avoid errors that can be difficult to detect.

What is a Shallow Copy?

A shallow copy copies only the first level of an object, leaving references to the original data at deeper levels. This means that if the original object has other objects inside it (nested), shallow copy will only copy the references to those objects, not the objects themselves.

Example in JavaScript

const originalArray = [1, 2, [3, 4]];
const shallowCopy = originalArray.slice();

shallowCopy[2][0] = 99;

console.log(originalArray); // [1, 2, [99, 4]]
console.log(shallowCopy);   // [1, 2, [99, 4]]

Example in Python

import copy

original_list = [1, 2, [3, 4]]
shallow_copy = copy.copy(original_list)

shallow_copy[2][0] = 99

print(original_list)  # [1, 2, [99, 4]]
print(shallow_copy)   # [1, 2, [99, 4]]

Tip:

A shallow copy is useful when you know you don't need to modify nested objects. It is faster and consumes less memory than a deep copy.

Note:

In JavaScript, if you use Array.slice() or Object.assign(), you are doing shallow copy!

What is a Deep Copy?

A deep copy copies all levels of an object, duplicating even nested structures. This means that any changes made to the copy will not affect the original object.

Example in JavaScript

const originalArray = [1, 2, [3, 4]];
const deepCopy = JSON.parse(JSON.stringify(originalArray));

deepCopy[2][0] = 99;

console.log(originalArray); // [1, 2, [3, 4]]
console.log(deepCopy);      // [1, 2, [99, 4]]

Example in Python

import copy

original_list = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original_list)

deep_copy[2][0] = 99

print(original_list)  # [1, 2, [3, 4]]
print(deep_copy)      # [1, 2, [99, 4]]

Tip:

If you are working with complex or nested data structures, deep copy is the safest option to avoid unwanted side effects.

Note:

In Python, copy.deepcopy() is your friend when you need to safely duplicate complex objects.

Direct Comparison: Shallow Copy vs Deep Copy

Here is a direct comparison between shallow copy and deep copy:

Feature Shallow Copy Deep Copy
Shallow copy Yeah No
Deep copy No Yeah
Modifications to the original object affect the copy Yeah No
Complexity Low High

Tip:

Remember, a shallow copy is faster, but a deep copy is safer when working with complex objects.

Common Use Cases

When to Use Shallow Copy

  • When you work with objects or simple data structures.
  • When you need to improve performance and deep modifications are not a problem.
  • Examples: Application configurations, temporary data mirroring.

When to Use Deep Copy

  • When you work with nested or complex data structures.
  • When you need to ensure that changes to the copy do not affect the original.
  • Examples: Complex data manipulation, applications that require high security and consistency.

Note:

Shallow copies are great for duplicating lightweight application settings or temporary data!

Common Problems and How to Avoid Them

Problems with Shallow Copy

A common mistake is to use a shallow copy instead of a deep copy when data is nested. This can lead to unwanted modifications to the original object.

Example:

const originalArray = [1, 2, [3, 4]];
const shallowCopy = originalArray.slice();

shallowCopy[2][0] = 99;

console.log(originalArray); // [1, 2, [99, 4]] (¡No esperado!)

Tip:

Always check if your object has nested levels before deciding between a shallow or deep copy.

Tools and Functions for Making Copies in JavaScript

Using Object.assign() for Shallow Copy

const originalObject = { a: 1, b: { c: 2 } };
const shallowCopy = Object.assign({}, originalObject);

Using ...spread for Shallow Copy

const originalArray = [1, 2, 3];
const shallowCopy = [...originalArray];

Using structuredClone() for Deep Copy

const originalObject = { a: 1, b: { c: 2 } };
const deepCopy = structuredClone(originalObject);

Tip:

structuredClone() is perfect for copying complex or circular structures without breaking your head.

Using Libraries like Lodash for Deep Copy

const _ = require('lodash');
const originalObject = { a: 1, b: { c: 2 } };
const deepCopy = _.cloneDeep(originalObject);

Tools and Functions to Make Copies in Python

Using the copy Module

import copy

original_list = [1, 2, [3, 4]]
shallow_copy = copy.copy(original_list)
deep_copy = copy.deepcopy(original_list)

Differences between copy.copy() and copy.deepcopy()

  • copy.copy(): Shallow copy.
  • copy.deepcopy(): Deep copy.

Note:

In Python, a shallow copy is sometimes all you need to avoid accidental changes to your lists!

Summary and Conclusion

In summary, both shallow copies and deep copies have their uses. The key is to understand the structure of the data you are working with and choose the appropriate copy method.

FAQs

1. Is shallow copy always faster than deep copy?

Yes, because it copies less data.

2. Can you do a deep copy without external libraries in JavaScript?

Yes, with JSON.parse(JSON.stringify()) or structuredClone().

3. What happens if I try to modify an object nested in a shallow copy?

The original object will also be affected.

4. Is it better to always use deep copy to avoid problems?

Not necessarily, only when you work with complex data structures.

5. What advantages does structuredClone() have over other deep copy methods in JavaScript?

It is native, supports circular structures and is more efficient than JSON.parse(JSON.stringify()), in addition to allowing values ​​to be completely transferred from one object to another.


Mistakes when using shallow copies instead of deep copies are more common than you think! I hope this little guide helps you avoid any problems when copying data.

Let me know in the comments, did you already know about deep and shallow copies and have you ever had a problem due to them?


Shallow Copy vs Deep Copy - ¿Qué son realmente? - Ejemplos con JavaScript y Python

BYXN's notebook? | Substack

My public notebook! ???. Click to read BYXN's notebook?, a Substack publication. Launched 17 days ago.

Shallow Copy vs Deep Copy - ¿Qué son realmente? - Ejemplos con JavaScript y Python bhyxen.substack.com

Photo by Mohammad Rahmani on Unsplash

Release Statement This article is reproduced at: https://dev.to/bhyxen/shallow-copy-vs-deep-copy-que-son-realmente-ejemplos-con-javascript-y-python-10ja?1 If there is any infringement, please contact study_golang @163.comdelete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3