[Study Chapter 3 every day and master js every week] Chapter 1st: variables, scopes, and memory problems

Source: Internet
Author: User


Section 1: variables-basic type and reference type

[Basic data type]: data segments stored in the stack, such as undefined, Null, boolean, Number, and String

Access by value, directly operate on the value in stack memory

[Reference Data Type]: objects stored in heap memory are of an unfixed size. The stack memory only saves the access address, such as Object/Date/Array/RegExp/Function.

Access by reference and access objects in [heap memory] through the storage address

Stack storage value and storage address

1. dynamic attributes

You can dynamically add attributes to the reference type for future use, while the basic type cannot be added.

For example:

1
Var person = new Object ();
2
Person. name = "jim ";
3
Alert (person. name );
2. Copy the variable value
The basic data type of replication is actually the data segment in the copied stack memory. The copied operation does not affect the original variable. The replication reference type is the address in the replication stack memory. The operation on this reference type is reflected in the original type, for example:

1
Var p1 = new Object ();
2
Var p2 = p1;
3
P1.name = "jim ";
4
Alert (p2.name); // It will also output jim
3. PASS Parameters

All function parameters in ECMAScript are passed by value.

When you pass a value of the basic type to a parameter, the passed value is copied to a local variable, that is, a named parameter, which is an element in the arguments object.

When a value of the reference type is passed to the parameter, the address of the stack memory is copied to a local variable. Therefore, the change of this local variable will cause the change of the original reference type, and then reflected outside the function.

Example:

1
Function showname (obj ){
2
Obj. name = "pp ";
3
}
4
Var person = new Object ();
5
Showname (person );
6
Alert (person. name); // pp
Correction: If the modified variables in the local scope are reflected in the global scope, it means that the parameters are passed by reference. (X)

Example:

1
Function showname (obj ){
2
Obj. name = "pp ";
3
Var obj = new Object ();
4
Obj. name = "pp2"
5
}
6
Var person = new Object ();
7
Showname (person );
8
Alert (person. name); // still output pp
Here, if the parameter is passed by reference, after the person is passed to the obj, The obj gets the pointer to the person. After obj re-defines the Object and changes the name to pp2, then the person will change accordingly. If it is a reference transfer, redefinition of obj is equivalent to redefinition of person through the pointer, the actual person. the name output is still pp, indicating that the person has not been changed. It proves that the parameter is not passed by reference!
Here, the person is actually the address where the person is saved in the stack memory and points to the object in the heap memory, that is, the person and obj objects point to the objects in the same heap memory. Then, after obj is redefined, obj no longer points to the original object, but to the newly created local object. According to the js operating mechanism, this object will be deleted immediately after the function is executed, the function cannot be accessed again.

4. Check the variable type

The typeof operator is a good helper for detecting basic type variables. To detect the reference type, you must use the instanceof operator.

Instanceof will detect which type of object is the reference type variable. For example:

1
Alert (person instanceof Object) // checks whether the person variable is of the Object type.
2
Alert (colors instanceof Array) // checks whether the colors variable is of the Array type.
3
//...........
Note: according to regulations, all reference type values are Objcect instances. Therefore, instanceof returns true when detecting a reference type value and the Object constructor.
BUG: When typeof is used to detect a function, this operator returns "function ". When typeof is used in safari and chrome to detect regular expressions, di returns "function" with an error ".

Section 2: execution environment and scope

1. Definition description

Variable object: Each execution environment has a corresponding variable object. All variables and functions defined in the environment are stored in this object, which cannot be accessed, however, the parser is called in the background.

Note: The Global execution environment on the web is the window object. Therefore, all global variables and functions are created as properties and methods of the window object.

Destruction of the environment: After all the code in the execution environment is executed, the environment will also be destroyed, and all variables and function definitions stored in the environment will also be destroyed. The global environment will not be destroyed until the program exits (for example, when the browser or webpage is closed.

Environment execution mechanism: each function has its own execution environment. When the execution stream enters a function, the function environment will be pushed into an environment stack. After the function is executed, the stack will bring up its environment, return the control to the previous execution environment.

Scope chain and Its Role: When the code is executed in an environment, the [scope chain] of the variable object will be created ]. The function of the scope chain is to ensure the orderly access of all variables and functions that the environment has the right to access.

2. extend the scope chain:

1
The following statement extends the scope chain:
2
 
3
Catch Block in the try-catch statement;
4
 
5
With statement;
Note:

Under normal circumstances, the variable object of the environment where the current code of the front-end of the scope chain is located.

However, these two statements temporarily Add a new variable object before the variable object. The temporary object will be deleted after execution.
Link: deep understanding of js function scopes and scope chains

Http://my.oschina.net/ws2042/blog/65257

3. Note -- js does not have block-level scope

Unlike other languages, js uses {} to indicate block-level scopes. js does not have block-level scopes. For example:

1
If (true ){
2
Var color = "red ";
3
}
4
Alert (color); // red
1
For (var I; I <10; I ++ ){
2
//....
3
}
4
Alert (I); // 10
In the above two examples, it is wrong in other languages with block-level scopes.
1. Declare the role of variables:

After a variable is declared using the var character, the variable is automatically added to the latest scope. If no var Declaration is available, the variable is added to the global scope by default.

For example:

1
Function test (){
2
Var a = 10;
3
Var B = 2;
4
C = a + B;
5
}
6
Test ();
7
Alert (a); // error
8
Alert (B); // error
9
Alert (c); // 12
2. query identifier:

When an identifier is introduced for reading or writing in an environment, you need to search to determine what the identifier represents. The search process starts from the frontend of the scope and goes up to query the identifiers that match the given name. If it is found in a local environment, it is stopped and the variable is ready. If the local environment does not exist, the search continues along the scope chain.

As mentioned before, the front end of each environment scope is generally the variable objects of all variables and functions in this scope, and the js parser will access them. The variable object is searched for in the upstream search. For more information, see the Reference Links in the above section.

Therefore, in terms of reading speed, local variables are faster than global variables.

 

Section 3rd: memory problems-garbage collection

Compared with other languages, js has a convenient feature in terms of garbage collection and memory release. Without manual memory tracing, these js parsers will automatically release the memory.

1. Garbage collection policy:

Mark Clear
Reference count
For more information, see.

2. Performance problems

This section describes the performance problems caused by different browser garbage collection policies:

First, the notorious IE6:

In IE6, garbage collection runs based on the memory allocation volume. When there are 256 variables, 4096 objects (or arrays), and any one of the array elements or 64 K strings meets the requirements, the garbage collector runs.

This also produces a problem that exists in ie6. If a js contains so many variables mentioned above, the script may keep so many variables throughout the lifecycle, so that the Garbage Collector runs frequently, resulting in serious performance problems.

The collection policy in IE7 has been fixed. The critical values in ie7 are the same as those in ie6. The difference is that when the amount of garbage collection memory is less than 15% of the total, this critical value will double. If the amount of memory collected reaches 85%, the default critical value of hui'fu is used.

Performance problems caused by referencing a counting policy:

A browser that uses the reference counting policy as the garbage collection mechanism. When a circular reference occurs in a js script, the reference number of the variable that is referenced in a circular reference will never be 0, then these two variables will not be recycled, resulting in a waste of memory.

For example:

1
Function family (){
2
Var a = new Object ();
3
Var B = new Object ();
4
A. brother = B;
5
B. sister =;
6
}
7
// In this example, a and B form a circular reference. The Garbage Collector of the reference count policy will not recycle it, even if the local scope has been destroyed. A and B will still occupy the memory.
The same tragedy is:
This problem also occurs when accessing non-native javascript objects in IE, because IE does not have native js objects, for example, the objects in BOM and DOM are implemented in the form of COM (Component Object Model) objects, and the garbage collection mechanism in COM is reference counting.

To solve the memory issue caused by cyclic references, it is best to manually disconnect the referenced variables without using them.

For example:

1
Var element = document. getElementBtId ("some_element ");
2
Var myObject = new Object ();
3
MyObject. element = element;
4
Element. someObject = myObject;
5
 
6
// Disconnect the reference in this way
7
 
8
MyObject. element = null;
9
Element. someObject = null;
3. Manage memory

Ensure that the js function is not affected, while the js occupies the least memory, which can improve web performance.

The best way to optimize memory usage is to save only necessary data for the code in execution. Once the data is no longer useful, it is best to set its value to null to release its reference-this method is called: Release the reference.

This method applies to most global variables and Global Object Attributes. Local variables are automatically removed when they leave the execution environment.

 
01
Function test (){
02
Var c = new Object ();
03
C. name =;
04
Return c;
05
}
06
 
07
Var B = test (2 );
08
 
09
// After B is used, set null to remove its reference. In this way, B is out of the running environment and will be recycled the next time it is recycled.
10
 
11
Var B = null;
 
Author: the soul of freedom

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.