What is the difference between deep copy and shallow copy? How to implement a deep copy?

1. Data type storage

As we mentioned in the previous article, JavaScriptthere are two major data types in :

  • basic type
  • reference type

Basic type data is stored in stack memory

The reference type data is stored in the heap memory, and the variable of the reference data type is a reference to the actual object in the heap memory, which is stored in the stack

Two, shallow copy

        Shallow copy refers to the creation of new data that has an exact copy of the original data's attribute values.

        If the attribute is a primitive type, the value of the primitive type is copied. If the attribute is a reference type, the memory address is copied.

       That is, a shallow copy is to copy a layer, and a deep reference type shares a memory address.

The following is a simple implementation of a shallow copy

In JavaScript, there are shallow copy phenomena:

  • Object.assign
  • Array.prototype.slice()Array.prototype.concat()
  • Copy using the spread operator

Object.assign

slice()

concat()

 

spread operator 

3. Deep copy 

       Deep copy creates a new stack. The properties of the two objects are the same, but they correspond to two different addresses. Modifying the properties of one object will not change the properties of the other object.

Common deep copy methods are:

  • _.cloneDeep()

  • jQuery.extend()

  • JSON.stringify()

  • handwritten loop recursion

.cloneDeep()

 JSON.stringify()

But this method has disadvantages, it will ignore undefined, symboland函数 

loop recursion 

Fourth, the difference 

        From the above figure, it is found that both shallow copy and deep copy create a new object, but when copying object properties, the behavior is different.

       Shallow copy only copies the pointer that the attribute points to an object, but not the object itself. The old and new objects still share the same memory, and modifying the object attributes will affect the original object.

 

       But deep copy will create an identical object, the new object does not share memory with the original object, and modifying the new object will not change the original object.

summary

The premise is that the copy type is a reference type:

  • Shallow copy is to copy one layer. When the attribute is an object, shallow copy is to copy. Two objects point to the same address

  • Deep copy is a recursive copy of the deep layer. When the attribute is an object, the deep copy is a new stack, and the two objects point to different addresses.

 

Guess you like

Origin blog.csdn.net/weixin_66375317/article/details/125056477