1024programmer Java In JavaScript, why should you use local variables whenever possible? _javascript skills

In JavaScript, why should you use local variables whenever possible? _javascript skills

If you don’t do this, how much loss will it cause to performance? This article will explore the answers to these questions and fundamentally understand what factors are related to the reading and writing performance of variables.
Copyright Statement


This article was translated from Nicholas C. Zakas on personal website< on February 10, 2009 "Javascript Variable Performance” published on /FONT>. Original text is the only official version. This article is a Simplified Chinese Translation authorized by the original author (Nicholas C. Zakas). The translator (明达) has made a lot of efforts to ensure the accuracy of the translation, and promises that the content of the translation is completely faithful to the original text, but it may still contain omissions and inaccuracies. Welcome everyone Correction. The content of the translation notes is informal and represents only the translator’s personal views.


The following is a translation of the original text:


On the issue of how to improve the performance of Javascript, the most commonly heard suggestion is to use local variables instead of global variables. This advice has always stuck with me and never been questioned in my nine years of working in web development, and the basis for this advice comes from Javascript’s handling of scoping and identifier resolution. (identifier resolution) method.


First of all, we must make it clear that functions are embodied as objects in Javascript. The process of creating a function is actually the process of creating an object. Each function object has an internal property called [[Scope]], which contains the scope information when the function was created. In fact, the [[Scope]] attribute corresponds to a list of objects (Variable Objects), and the objects in the list can be accessed from within the function. For example, if we create a global function A, then A’s [[Scope]] internal property contains only one global object (Global Object), and if we create a new function B in A, then B’s [[Scope] ] attribute contains two objects, the Activation Object object of function A is in the front, and the global object (Global Object) is in the back.


When a function is executed, an executable object (Execution Object) will be automatically created and bound to a scope chain (Scope Chain). The scope chain will be established through the following two steps for identifier resolution.


1. First, copy the objects in the internal properties of the function object [[Scope]] to the scope chain in order.
2. Secondly, when the function is executed, a new Activation Object object will be created. This object contains the definitions of this, parameters (arguments), and local variables (including named parameters). This Activation Object object will be Placed at the front of the scope chain.


During the execution of Javascript code, when an identifier is encountered, it will be searched in the scope chain of the execution context (Execution Context) based on the name of the identifier. Starting from the first object in the scope chain (the Activation Object of the function), if not found, search for the next object in the scope chain, and so on, until the definition of the identifier is found. If the last object in the scope, which is the Global Object, is not found after searching, an error will be thrown, prompting the user that the variable is undefined. This is the function execution model and identifier resolution (Identifier Resolution) process described in the ECMA-262 standard. It turns out that most Javascript engines are indeed implemented this way. It should be noted that ECMA-262 does not mandate the use of this structure, but only describes this part of the function.


After understanding the process of identifier resolution (Identifier Resolution), we can understand why local variables are resolved faster than variables in other scopes, mainly because the search process is greatly shortened. But how much faster will it be? To answer this question, I simulated a series of tests to test the performance of variables at different scope depths.


The first test is to write the simplest value to a variable (the literal value 1 is used here). The result is shown in the figure below, which is very interesting:



It is not difficult to see from the results that when the identifier parsing process requires deep search, it will be accompanied by performance loss, and the degree of performance loss will increase as the depth of the identifier increases. Unsurprisingly, Internet Explorer performed the worst (but to be fair, there were some improvements in IE 8). It is worth noting that there are some exceptions here, Google Chrome and the latest midnight version of WebKit have a very stable access time to variables and do not increase with increasing scope depth. Of course, this should be attributed to the next generation Javascript engines they use, V8 and SquirrelFish. These engines perform optimizations when executing code, and it’s clear that these optimizations makeInterrogating variables is faster than ever. Opera also performed well, being much faster than IE, Firefox and the current version of Safari, but slower than browsers based on V8 and Squirrelfish. The performance of Firefox 3.1 Beta 2 is a bit unexpected. The execution efficiency of local variables is very high, but as the number of scope layers increases, the efficiency is greatly reduced. It should be noted that I am using the default settings here, which means that the Trace function is not turned on in Firefox.


The above results were obtained by performing write operations on variables. In fact, I was curious whether the situation would be any different when reading variables, so I did the following test. It was found that the reading speed is slightly faster than the writing speed, but the trend of performance changes is consistent.



Same as the previous test, Internet Explorer and Firefox were still the slowest, Opera showed very eye-catching performance, and similarly, Chrome and the latest version of Webkit Midnight Edition showed performance trends independent of scope depth. Similarly, It should be noted that the variable access time of Firefox 3.1 Beta 2 will still have a strange jump with depth.


During the testing process, I discovered an interesting phenomenon, which is that Chrome will have additional performance losses when accessing global variables. The time to access global variables has nothing to do with the scope level, but it will be 50% longer than the time to access local variables of the same level.


What enlightenments can these two tests bring us? The first is to verify the old point of view, which is to use local variables as much as possible. In all browsers, accessing local variables is faster than accessing variables across scopes, including global variables. The following points should be based on the experience gained through this test:


* Carefully check all the variables used in the function. If there is a variable that is not defined in the current scope and is used more than once, then we should save this variable in a local variable and use this local variable to proceed. Read and write operations. This can help us reduce the search depth of variables outside the scope to 1. This is especially 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 will modify the scope chain of the execution context (Execution Context) and add an object (Variable Object) at the front. This means that during the execution of with, the actual local variables are moved to the second position on the scope chain, which will cause a performance loss.
* If you are sure that a piece of code will definitely throw an exception, then avoid using try-catch, because the catch branch is processed in the same scope chain as with. However, there is no performance loss in the try branch code, so it is still recommended to use try-catch to catch unpredictable errors.


If you want more discussion around this topic, I gave a small talk at last month’s Mountain View Javascript Meetup. You can download slides on SlideShare, or watch the full video of the party. My speech starts at about 11 minutes.


Translator’s Notes


If you have any doubts while reading this article, it is recommended to read the following two articles:
* “Javascript Object Model-Execution Model” written by Richie
* “ECMA-262 Third Edition“, mainly look at Chapter 10, which is the execution context (Execution Context), the nouns mentioned in this article are there detailed explanation.


At the end, Nicholas mentioned a Mountain View Javascript Meetup. The Meetup website is actually an organization website for various real-world activities. You need to bypass the firewall to access it. I am really happy to live in California. There are so many good activities. You can participate, haha.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/in-javascript-why-should-you-use-local-variables-whenever-possible-_javascript-skills-2/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

The latest and most comprehensive programming knowledge, all in 1024programmer.com

© 2023 1024programmer - Encyclopedia of Programming Field
Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

首页
微信
电话
搜索