JS Advanced Programming (iv) variables, scope, and memory issues

Source: Internet
Author: User
Tags getcolor

Values for base types and reference types

The ECMAScript variable may contain values for two different data types: the base type value and the reference type value. Primitive type values refer to Undefined, Null, Boolean, number, and String, whereas reference-type values refer to objects that may consist of multiple values. The base data type is accessed by value , and the value of the reference type is accessed by reference .

Dynamic Properties

For values of reference types, we can add properties and methods to them, and you can change and delete their properties and methods.

var New  = "Nicholas"//"Nicholas"

We cannot add properties to the values of the base type, although doing so does not result in any errors.

var name = "Nicholas"=+//undefined

Copy variable values

If you copy the value of the base type from one variable to another, a new value is created on the variable object, and the value is copied to the location assigned to the new variable.

When a value of a reference type is copied from one variable to another, the value stored in the variable object is also copied into the space allocated for the new variable. The difference is that a copy of this value is actually a pointer to an object stored in the heap. When the copy operation is finished, two variables will actually refer to the same object.

Passing parameters

When you pass a value of a primitive type to a parameter, the passed value is copied to a local variable.

When a value of a reference type is passed to a parameter, the address of the value in memory is copied to a local variable, so the change of the local variable is reflected outside the function.

function= "Nicholas"new= "Greg";} var New  //"Nicholas"

So when a function parameter passes a reference type or is passed by value, the special value of the reference type is passed.

Detection type

typeof is used when detecting the base data type, but the instanceof operator is used when detecting reference type data.

instanceofinstanceof Object);  // is the variable person an Object?  instanceof//  variable colors is an Array?  instanceof//  variable pattern is REGEXP? 

If the variable is an instance of a given reference type (identified by its prototype chain), then the instanceof operator returns TRUE.

Execution Environment and scope

The execution environment defines other data that a variable or function has access to. Each execution environment has a variable object associated with it (variable object), and all variables and functions defined in the environment are stored in the object. The global execution environment is one of the outermost execution environments. In a Web browser, the global execution environment is considered a Window object, and all global variables and functions are created as properties and methods of the Window object. after all code in an execution environment is executed, the environment is destroyed, and all variables and function definitions stored therein are destroyed (the global execution environment is not destroyed until the application exits-for example, when the Web page or browser is closed). Each function has its own execution environment. When the execution flow enters a function, the environment of the function is pushed into an environment stack. After the function executes, the stack pops up its environment and returns control to the previous execution environment.

When code executes in an environment, a scope chain of variable objects is created (scope chain). The purpose of a scope chain is to ensure sequential access to all variables and functions that the execution environment has access to. The front end of the scope chain, which is always the variable object for the environment in which the code is currently executing. If the environment is a function, its active object (activation object) is used as the variable object. The active object initially contains only one variable, the arguments object (this object does not exist in the global environment). The next variable object in the scope chain comes from the containing (external) environment, and the next variable object comes from the next containment environment. In this way, it continues to the global execution environment; The variable object of the global execution environment is always the last object in the scope chain.

Identifier parsing is the process of searching identifiers one level at a scope chain. The search process always starts at the front end of the scope chain, and then goes backward backwards until the identifier is found (if an identifier is not found, this usually results in an error).

varcolor = "Blue";functionChangeColor () {varAnothercolor = "Red"; functionswapcolors () {varTempcolor =Anothercolor; Anothercolor=color; Color=Tempcolor;//Here you can access color, Anothercolor, and Tempcolor    }//you can access color and anothercolor here, but you cannot access Tempcolor    swapcolors ();}//only color can be accessed hereChangeColor ();

The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions in the internal environment. The linkages between these environments are linear and sequential. Each environment can search up the scope chain to query for variables and function names, but any environment cannot enter another execution environment by searching down the scope chain.

Extend the scope chain

The catch block and the with statement of the Try-catch statement can extend the scope chain, which adds the variable object to the scope chain front end.

No block-level scopes

if (true) {  var color = "Blue"//"Blue"
 for (var i=0; i <; i++) {    //

In JavaScript, variables declared in the IF statement and for loops persist after the statement is executed and are added to the current execution environment.

declaring variables

Variables declared with Var are automatically added to the closest environment. Within the function, the closest environment is the local environment of the function, and in the With statement, the closest environment is the function environment. If you initialize a variable without using the var declaration, the variable is automatically added to the global environment.

 function   add (NUM1, num2) { var  sum = num1 + num2;  return   sum;}  var  result = Add (10, 20); // 30  alert (sum); //  because sum is not a valid variable, it causes an error  
function Add (NUM1, num2) {    = num1 + num2;     return sum;} var //  - //  -

Query identifiers

When you reference an identifier in an environment for reading or writing, you must search to determine what the identifier actually represents. The search process starts at the front end of the scope chain and queries the identifiers that match the given name upwards. If the identifier is found in the local environment, the search process stops and the variable is ready. If the variable name is not found in the local environment, it continues to search up the scope chain. The search process goes back to the variable object of the global environment. If the identifier is not found in the global environment, it means that the variable is not yet declared.

var color = "Blue"; function GetColor () {    return//"Blue"

var color = "Blue"; function GetColor () {    var color = "Red";     return  //"Red"

Garbage collection

JavaScript has an automatic garbage collection mechanism that identifies those changes that are no longer being used , and then frees up the memory they occupy.

Mark Clear

The most common method of garbage collection in JavaScript is tag cleanup . When a variable enters the environment (for example, a variable is declared in a function), the variable is marked as "entering the environment." When the variable leaves the environment, it is marked as "out of the environment."

The garbage collector will tag all variables stored in memory at run time (of course, you can use any markup method). It then removes the variables in the environment and the tags of the variables referenced by the variables in the environment. Variables that are tagged later will be considered as variables to be deleted because variables in the environment are inaccessible to those variables. Finally, the garbage collector completes the memory cleanup work, destroys those tagged values, and reclaims the memory space that they occupy.

Reference count

Another less common garbage collection strategy is called reference counting .

The meaning of the reference count is the number of times each value is referenced by the tracking record. When a variable is declared and a reference type value is assigned to the variable, the number of references to that value is 1. If the same value is assigned to another variable, the number of references to that value is added by 1. Conversely, if a variable that contains a reference to this value has another value, the number of references to the value is reduced by 1. When the number of references to this value becomes 0 o'clock, it means that there is no way to access the value again, so that it can reclaim the memory space it occupies.

Netscape Navigator 3.0 is the first browser to use a reference counting strategy, but soon it encounters a serious problem : circular referencing . A circular reference refers to a pointer to object B that is contained in object A, and object B contains a reference to object A.

function problem () {    varnew  Object ();     var New Object ();     = OBJECTB;     = objecta;}

In this example, Objecta and OBJECTB are referred to each other by their respective properties, that is, both objects have a reference count of 2. In implementations that take a markup cleanup policy, these two objects leave the scope after the function executes, so this mutual reference is not an issue. However, in implementations with reference counting policies, objecta and OBJECTB will continue to exist when the functions have been executed, because their references will never be 0. If this function is repeated multiple calls, it will result in a large amount of memory not being recycled. To do this, Netscape discarded the reference counting method in Navigator 4.0, instead of using tag cleanup to implement its garbage collection mechanism.

Some of the objects in IE are not native JavaScript objects. For example, the objects in their BOM and Dom are implemented using C + + as COM (Component object model, Component object models) objects, and the garbage collection mechanism of COM objects is a reference counting strategy. Therefore, even though the JavaScript engine of IE is implemented using the tag purge policy, the COM objects that JavaScript accesses are still based on the reference counting policy. In other words, whenever a COM object is involved in IE, there is a circular reference problem.

var element = document.getElementById ("some_element"); var New  == myObject;

This example creates a circular reference between a DOM element and a native JavaScript object (myObject). Where the variable MyObject has a property named element pointing to the element object, and the variable element has a property called the Someobject callback MyObject. Since this circular reference exists, even if the DOM in the example is removed from the page, it will never be recycled.

To avoid circular reference problems like these, it is best to manually disconnect the native JavaScript object from the DOM element when you do not use them.

Nullnull;

Setting a variable to null means that the connection between the variable and the value it previously referred to is cut off. The next time the garbage collector runs, the values are removed and the memory they occupy is reclaimed.

To solve these problems, IE9 has converted both BOM and Dom objects into real JavaScript objects. This avoids the problems caused by the coexistence of two garbage collection algorithms, and eliminates the common memory leaks.

Performance issues

The garbage collector runs periodically, and if the amount of memory allocated to a variable is significant, the amount of recycling is considerable. In this case, determining the time interval for garbage collection is a very important issue.

IE's garbage collector runs according to the amount of memory allocated, specifically 256 variables, 4,096 objects (or array) literals and arrays of elements (slots), or 64KB strings. If any of these thresholds are reached, the garbage collector runs. The problem with this implementation is that if a script contains so many variables, it is likely that the script will retain so many variables throughout its life cycle. In this way, the garbage collector has to run frequently. As a result, the severity problem caused by this has prompted IE7 to rewrite its garbage collection routines.

With the release of IE7, the garbage collection routines of its JavaScript engine have changed the way it works: variable allocations that trigger garbage collection, literals, and (or) critical values of array elements are adjusted for dynamic remediation. The critical values in the IE7 are equal to IE6 at the initial time. If the garbage collection routine reclaims less than 15% of the memory allocated, the thresholds for variables, literals, and/or array elements are doubled. If the routine reclaims 85% of the memory allocations, resets the various thresholds back to the default values. This seemingly simple adjustment greatly improves the performance of IE when running pages that contain a lot of JavaScript.

Managing Memory

The amount of available memory allocated to a Web browser is typically less than that allocated to a desktop application. This is done primarily for security reasons, in order to prevent the Web page running JavaScript from exhausting all system memory and causing the system to crash.

Ensure that the least amount of memory is used for better performance of the page. The best way to optimize memory consumption is to save only the necessary data for the code in execution. Once the data is no longer useful, it is best to release its reference by setting its value to null-this is called de-referencing (dereferencing).

This practice applies to most global variables and properties of global objects. Local variables are automatically dereferenced when they leave the execution environment.

function Createperson (name) {    varnew  Object ();     = name;     return Localperson;} var globalperson = Createperson ("Nicholas"); // manually de-Globalperson references null;

Releasing a reference to a value does not mean that the memory consumed by the value is automatically reclaimed. The real effect of dereferencing is to leave the value out of the execution environment so that it can be reclaimed the next time the garbage collector runs.

JS Advanced Programming (iv) variables, scope, and memory issues

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.