Javascript notes: Improve javascript code performance through in-depth understanding of the scope chain and execution environment

Source: Internet
Author: User

 

In the previous article, I ended the creation of objects and finally introduced the issue of scope chain and execution environment. When I have a deeper understanding of this knowledge, I will look back at the jQuery source code to know how powerful the code written by masters is, the jQuery source code uses the scope chain and execution environment knowledge to improve program performance.

Okay, no nonsense. The scope mentioned in the previous blog is relatively simple. In fact, understanding the scope is the key to understanding the entire javascript language. In particular, when I wrote javascript notes, I had a hard time understanding many weird javascript usage, the reason is that the concept of scope in javascript is not really understood.

What is the scope of Javascript? The scope determines the variables that can be accessed by the function (note: the scope is the internal attribute of the function and the scope is the function that cannot be bypassed). The scope also determines the direction of the this pointer. In the previous blog, I said that a program is actually a process of constantly retrieving data, so the efficiency of data retrieval determines the performance of the program. Therefore, since the scope determines that those variables can be accessed, of course, it also determines the way to retrieve these variables, so it is critical to write an efficient javascript program to flexibly use the principle of scope.

In the previous blog, I wrote a function with the following code:

<Script type = "text/javascript">

Function add (a, B)

{

Var sum = a + B;

Return sum;

}

</Script>

 

You can see that this function belongs to window rather than function. When the page is loaded, the add function will be initialized to generate its own scope chain, in the previous article, I set the breakpoint debugging in firebug and posted a variable diagram. I thought this was the variable included in the Scope of the function add. Now I found that it was wrong, those variables are the "Global Environment" of the window, rather than the variable map of the Scope attribute of the add function. Here I will correct it.

Next I will focus on the scope chain and execution environment, which I mentioned in the javascript Object creation Article. Here I will review the knowledge:

What is the execution environment? In javascript, the execution environment is divided into two types: global environment and local environment. The shared methods and attributes on the entire page are in the global environment, the execution environment in function {} is a local environment. The execution environment defines other data that variables or functions have the right to access and determines their respective behaviors, each execution environment defines a variable object related to it. All variables and functions defined in the environment are stored in this object, although the code we write cannot access this object, however, the parser will use it in the background when processing data.

The global execution environment is also the peripheral execution environment, which is within the scope of the web browser, the global scope is different from the global scope of javascript. The Global execution environment is considered a window object. Therefore, global variables and functions are created as methods and properties of the window object, the global execution environment knows that the application will be destroyed only when it exits, for example, the web page is closed or the browser is closed. The local environment uses the function object as the correlated object.

 

Note that the Environment prefix is: execution, that is, only the function is executed (partial execution environment) and the page is loaded (Global execution environment ), the following is the global execution environment variable when the page is loaded:

 

 

Now we have to execute the add function. The Code is as follows:

Function add (a, B)

{

Var sum = a + B;

Return sum;

}

 

Console. log (add (10, 20 ));

 

  

This is the variable graph of the execution environment of the add function:

1. firebug:

 

 

2. chrome code Debugger:

 

 

The code structure is as follows:

 

 

When a function is executed, the function creates an internal object named "execution context". In my understanding, the runtime context is the execution environment of the function, each runtime context has its own scope chain for identifier parsing.

When the runtime context is created, its Scope chain is initialized to the objects contained in the Scope attribute of the current running function (see the memory diagram in firebug and chrome debugger, for example, in addition to a, B, sum, this, and arguments, the add function cannot be seen in the firebug and chrome debugger ). These values are copied to the scope chain of the execution period context in the order they appear in the function. Once this process is completed, a new object called "activation object" is created for the context during the execution period, and the activity object is a variable object during the function runtime, contains all local variables, named parameters, parameter sets, and this. This object is then pushed to the frontend of the scope chain. When the runtime context is destroyed, the active object is also destroyed. During function execution, an identifier is parsed every time a variable is encountered. This resolution determines where we get the variable or store the variable, this process searches for the scope chain of the context of the entire function runtime, and finds the identifiers with the same name. The search process starts from the scope header, that is, the activity object of the currently running function. If it is found, use it. If it is not found, it will continue to search for the next object in the scope chain. The search process will continue until the identifier is found or not found. In this case, the identifier is not defined.

Variables used in javascript are used for identifier parsing. From the above explanation, we know that identifier parsing must consume computer performance. When the identifier is located in the execution context scope chain, the performance slows down, so what is the slowest? For example, if we find that global variables are always slower than local variables in the function, if we define a more complex function with multiple layers of nesting, accessing global variables is a nightmare of performance. Therefore, we try to use as many local variables as possible in the function. (Due to the differences in browser products, the performance of access variables in Some browsers may be different, but in general, access function local variables are always the fastest ).

Using local variables whenever possible brings about a very important usage to improve program performance: using global variables within a function is a cross-scope operation, if a cross-scope value is used more than once within the function, we store it in a local variable.

The code writing format is:

Function ftn ()

{

Var doc = document;

.......

}

 

 

Use var to define global variables into local variables.

This usage is clear at the beginning of jQuery source code:

Var jQuery = function (selector, context ){

// The jQuery object is actually just the init constructor 'enabled'

Return new jQuery. fn. init (selector, context );

},

 

// Map over jQuery in case of overwrite

_ JQuery = window. jQuery,

 

// Map over the $ in case of overwrite

_ $ = Window. $,

 

// Use the correct document accordingly with window argument (sandbox)

Document = Legal disclaimer Doc ument,

 

JQuery stores frequently used global variables in the local variables of the function.

  

From the summer forest

Related Article

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.