An introduction to deep and shallow copy in JavaScript
Basic introduction to
-
ECMAScript variables contain values for two data types: base data type and reference data type.
-
Basic data types: Boolean, Null, Undefined, Number, String, Symbol (new in ES6). Names and values are stored in stack memory.
-
Reference Data types: Object, Array, Function, Data, RegExp, etc. The name is stored in the stack, the value is stored in the heap, and the stack memory provides a reference address to the value in the heap memory.
-
Shallow copy: used when an assignment of a reference data type is affected by the original data. That is, copying the value of a reference type from one variable to a new variable is essentially copying a pointer, and both variables end up pointing to the same object. Another popular example is that when a man stands in the sun, his shadow moves as the man moves.
-
Deep copy: Used to assign values to primitive data types without affecting the original data. That is, one variable copies the value of the base type to another new variable, giving the value to the new variable, and creating a copy of the value to the new variable. A popular example is that passer-by b built a villa, passer-by A also built a same, if they go to decorate, the two villas have changed, but the two do not affect each other.
Depth copy implementation
Deep copy
let a = 1;
let b = a; // Create a new space and assign it to 1,
a = 2
console.log(a); / / 2
console.log(b); / / 1
Copy the code
Shallow copy
- If you change the value of the name attribute in d or C, both will make the same change because they are accessing the same address.
function foo() {
var a ='甲'
var b = a
var c = {name :'乙'}
var d = c
console.log(d); // {name :' b '}
}
foo()
Copy the code
- Null clears the pointer to A, the value (address) of the a variable on the stack, but does not affect B
let a = {name: "Xue Zhiqian"}
let b = a;
a = null
console.log(a); //null
console.log(b); // {name: "xue Zhiqian "}
Copy the code
Small development
The JavaScript heap does not require program code to be explicitly released, because the heap is handled by automatic garbage collection, which is different for each JavaScript interpretation engine in each browser
As a basic rule, if there is no reference to an object in the stack, the object is considered no longer needed and its memory is cleared at garbage collection.
Therefore, references to objects should be released when they are not needed in order to facilitate garbage collection, thus improving the performance of the program.