In JavaScript, why do you use local variables whenever possible? _javascript Tips

Source: Internet
Author: User
Tags object model
How much damage can be done to performance without doing so? This article explores the answers to these questions and fundamentally understands what factors are involved in the reading and writing properties of variables.
Copyright Notice

This article is translated from the "JavaScript Variable Performance" published on the personal website by Nicholas C. Zakas on February 10, 2009. The original version is the only official edition, and this is a simplified Chinese translation (Simplified Chinese translation) authorized by the original author (Nicholas C. Zakas). The translator ( informed ) has made a lot of efforts in the accuracy of translation, and promised that the content of the translated text is completely loyal to the original, but may still contain omissions and irregularities, and you are welcome to correct me. The content is informal and represents only the translator's personal point of view.

The following is the translation of the original text:

One of the most common suggestions for how to improve JavaScript performance is to use local variables (global variables) as much as possible instead of variables. In my nine years of web development work, this advice has always been in my ear and has never been questioned, and the basis of this proposal comes from the way JavaScript handles scopes (scoping) and identifier parsing (identifier resolution).

First, we need to be clear that the function in JavaScript as a specific object, the process of creating a function, in fact, is the process of creating an object. Each function object has an internal property called [[Scope]], which contains the scope information when the function is created. In fact, the [[Scope]] property corresponds to a list of objects (Variable Objects) that can be accessed from within a function. For example, if we build a global function A, then the [[scope]] internal property of a has only one global object, and if we create a new function B in a, then the [[scope]] property of B contains two objects. Function A's activation object is preceded by a global object, which is in the back row.

When a function is executed, a executable object (Execution object) is automatically created, and a scope chain (scope Chain) is bound at the same time. The scope chain is established using the following two steps for identifier resolution.

1. First, the objects in the function object [[Scope]] Internal property are copied sequentially into the scope chain.
2. Second, when the function executes, a new activation object is created that contains the definition of this, parameters (arguments), local variables (including named arguments), and this activation Object objects are placed at the front of the scope chain.

In the process of executing JavaScript code, when an identifier is encountered, the search is performed in the scope chain of the execution context (Execution contexts) based on the name of the identifier. Starts from the first object in the scope chain (the function's activation object) and, if not found, searches for the next object in the scope chain, and so forth, until the definition of the identifier is found. If the last object in the scope is not found after searching, that is, the global object, an error is thrown that prompts the user that the variable is undefined (undefined). This is the process of performing the function execution model and identifier parsing (Identifier resolution) described in the ECMA-262 standard, and it turns out that most JavaScript engines do. It should be noted thatECMA-262 does not enforce the requirement for this structure, but only describes this part of the function.

After understanding the process of identifier parsing (Identifier resolution), we can see why local variables are faster to parse than other scoped variables, mainly because the search process is significantly shortened. But how much faster will it be? To answer this question, I simulated a series of tests to test the performance of variables in different scoping depths.

The first test is to write one of the simplest values to a variable (the literal value 1 is used here), and the results are shown in the following illustration, which is interesting:

It is not difficult to see from the results that when the identifier parsing process requires a deep search, it will be accompanied by performance loss, and the degree of performance loss will increase as the identifier depth increases. Unsurprisingly, Internet Explorer is the worst performer (but, to be fair, IE 8 has some improvement). It is noteworthy that there are some exceptions, Google Chrome and the latest webkit in the time to access variables to maintain a stable, not with the scope of the increase in depth. Of course, this is due to the next generation of JavaScript engines, V8, and squirrelfish they use. These engines are optimized for code execution, and it is clear that these optimizations make accessing variables faster than ever. Opera is also very good, much faster than IE, Firefox and the current version of Safari, but slower than V8 and squirrelfish browsers. The Firefox 3.1 Beta 2 performance is a bit surprising and efficient for local variables, but as the number of scoping layers increases, efficiency is compromised. Note that I use the default settings here, which means Firefox does not have trace enabled.

The result is a write to the variable, in fact, I am curious to read the variable when the situation will be different, and then do the following test. The results showed that the speed of reading was faster than that of writing, but the trend of performance change was consistent.

Like the last Test, Internet Explorer and Firefox are the slowest, opera has a very eye-catching performance, and the same, Chrome and the latest version of the WebKit Midnight version shows the scope depth independent of performance trends, also need to note that the The Firefox 3.1 Beta 2 variable access time is still accompanied by a strange leap in depth.

In the course of the test, I found an interesting phenomenon, that is, chrome access to global variables when there is an additional performance loss. The time to access a global variable is not related to the scope layer, but it can be 50% more time than a local variable that accesses the same number of layers.

What can these two Tests bring to our inspiration? The first is to validate the old idea of using local variables as much as possible. In all browsers, accessing a local variable is faster than accessing a variable across a scope, including, of course, a global variable. Here are some of the lessons from this test:

* Carefully check all the variables used in the function, if a variable is not defined in the current scope and used more than once, then we should save the variable in a local variable, and use this local variable to read and write operations. This will help us reduce the search depth of scoped variables to 1. This is particularly important for global variables, because global variables are always searched at the last position of the scope chain.
* Avoid using the WITH statement. Because it modifies the scope chain of the execution context (Execution contexts), add an object (Variable objects) to the front. This means that in the execution of the with, the actual local variables are moved to the second position on the scope chain, which can result in a performance loss.
* If you are sure that a piece of code will throw an exception, avoid using Try-catch, because the catch branch has the same method of handling on the scope chain as with. But there is no performance penalty for the code in the try branch, so it is advisable to use try-catch to catch those unpredictable errors.

If you want to have more discussion around this topic, I made a small speech in last month's mountain View JavaScript Meetup . You can download slides on SlideShare, or watch the full video of the party, and my speech starts around 11 minutes or so.

Translator Notes

If you have any doubts in the course of reading this article, we suggest that you read the following two articles:
*JavaScript Object Model-execution model written by Richie
* "ECMA-262 third edition ", mainly look at the tenth chapter, is the execution context (Execution), the noun mentioned in this article there are detailed explanations.

At the end of the day, Nicholas mentions a mountain View JavaScript meetup,meetup that site is actually a variety of real world activities of the Organization site, need to turn over the wall to visit, live in California really happy, There are so many good activities to participate in, hehe.

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.