ECMAScript variables can contain two different types of data: raw and reference values
The difference between a native and a reference value
What is the original value:
The simplest values are Undefined, Null, Boolean, Number, String, Symbol, BigInt. A variable that holds the original value is accessed by value because we are manipulating the actual value stored in the variable
What is a reference value:
An Object consisting of multiple values, for example, Object. A reference value is an object that is stored in memory. The variable that holds the reference value is accessed by reference. Since JavaScript does not allow direct access to memory locations, it is actually the reference to the object that is manipulated rather than the actual object itself.
The difference between:
- Dynamic properties:
Raw value: no attribute reference value: Its attributes and methods can be added, modified, and removed at any time
- Copy the value:
Original value: Copy value variables can be used independently of each other.
let num=123; let num1=num; The console. The log (num, num1) / / 123123 num = 100; The console. The log (num, num1) / / 100123Copy the code
Reference value: a copy of a pointer on the stack (the address of an object in the heap) that points to the same object
let obj={name:"lly",sex:"Man"}
let obj1=obj;
console.log(obj,obj1)//{name:"lly",sex:"Man"},{name:"lly",sex:"Man"}
obj.age=20
console.log(obj,obj1)//{name:"lly",sex:"Man",age:20},{name:"lly",sex:"Man",age:20}
Copy the code
- Pass parameters:
Original value: Like a copy of the original value variable
function add(num) { num += 10; return num; } let count = 20; let result = add(count); console.log(count); // 20, no change console.log(result); / / 30Copy the code
Reference value: The same as copying reference value variables
function setName(obj) {
obj.name = "lly";
}
let person = new Object();
setName(person);
console.log(person.name); // "lly"
Copy the code
- Methods for judging types:
Original type value: typeof
Reference type value: instanceof
Comprehensive judgment method: Object. The prototype. ToString. Call (to determine the type of the value);
Execution context and scope
What is an execution context:
An abstraction of the context in which the current JavaScript code is being parsed and executed
The type of execution context
1. Global execution context
3. Function execution context
2. Block level execution context
What is scope:
An independent area that does not allow variables to be exposed is simply a space that isolates variables. Characteristics: variables with the same name do not conflict with each other in different scopes.
Type of scope:
- Global domain domain
- Function scope
- Block-level scope
The types and characteristics of variable declarations
- Var function scope declaration
There is variable promotion, and the same variable can be declared repeatedly in the same scope
- Let block-level scope declaration
There are also temporary dead zones where variable promotions are unavailable before a variable declaration and cannot be declared twice in the same scope
- Const constant declaration
The declared variable must be initialized at the same time, and cannot be reassigned once declared (for the initial value is the original value, cannot be reassigned; for the initial value is a reference value, cannot be reassigned to other references, there is no restriction on the reference worth key value), other characteristics are the same as let.
Garbage collection mechanism
JavaScript is a language that uses garbage collection. The execution environment is responsible for managing memory as the code executes. Automatic memory management is used to allocate memory and recycle idle resources. Make sure that the variable is not in use, then release the occupied memory. The marking strategy of garbage collection mainly adopts: mark cleaning and reference counting.
Principle of tag cleaning
Out-of-scope values are automatically marked as recyclable and then deleted during garbage collection, marking values that are not currently in use and then coming back to reclaim their memory
Principles of reference counting (uncommon)
Each value is referenced, and when the number of references is zero, the next time the garbage collector runs, the memory of the zero reference value is freed.
Rules for the number of citations:
When you declare a variable and assign it a reference value, the number of references to that value is 1. If the same value is assigned to another variable, the number of references is increased by one. Similarly, if the variable holding a reference to that value is overwritten by another value, the number of references is reduced by one
performance
The garbage collector runs periodically, and scheduling the garbage collector frequently can seriously affect performance, so browsers adopt a number of performance optimizations:
1. Generation collection:
Objects are divided into two groups: “new” and “old.” Many objects appear, do their job and die quickly, and they can be cleaned up quickly. Those that survive for a long time become “old” and are examined less often
2. Incremental collection:
If there are many objects and we try to traverse and mark the entire set of objects at once, it may take some time and introduce significant delays in execution. So the engine tries to break up garbage collection into several parts. Then these parts will be processed one by one. This requires extra markers between them to track changes, but there are many small delays instead of one big one.
3. Collect in your spare time:
The garbage collector only tries to run when the CPU is idle to reduce the possible impact on code execution.
Memory management
1. Improve performance with const and let declarations:
Since const and let are block-scoped rather than function scoped, let the garbage collector step in earlier and reclaim the memory that should be reclaimed earlier. To improve the garbage collection process.
2. Hide classes and delete operations:
Hidden classes:
The JavaScript engine introduced hidden classes to improve performance, and at runtime, V8 associates objects created with hidden classes to track their attribute characteristics.
function people() {
this.name= 'lly';
}
let a1 = new people();
let a2 = new people();
a2.sex="Man"
Copy the code
The solution is to avoid JavaScript’s “create first, complement later” type of dynamic attribute assignment and declare all attributes at once in the constructor.
function people(sex) {
this.name= 'lly';
this.sex=sex
}
let a1 = new people();
let a2 = new people("Man");
Copy the code
Delete operation:
Using the delete keyword causes the same hidden class fragment to be generated, and it is best practice to set unwanted attributes to NULL.
function people() { this.name= 'lly'; this.sex="Man" } let a1 = new people(); let a2 = new people(); delete a1.sex; A1. Sex =null// Best practiceCopy the code
3. Causes and solutions of memory leaks:
- Closures: Manually set null to cut off references
- Unexpected global variables: Use a strict schema or be preceded by a declaration key
- Timer: No timer is needed to clear the timer
- The DOM/BOM object leaks memory on the Window. onunload event
4. Static allocation and object pooling:
Object pooling:
A JavaScript optimized strategy for managing a collection of recyclable objects. An application can request an object from the object pool, set its properties, use it, and then return it to the object pool when the operation is complete. Since no object initialization occurs, garbage collection probes do not detect object turnover, and therefore the garbage collection program will not run as often
Static assignment:
An extreme form of optimization. If your application is seriously slowed down by garbage collection, you can use it to improve performance. But that’s not often the case. In most cases, this is premature optimization, so don’t worry about it.