Home > Article > Web Front-end > javascript Use local variables to replace global variables Page 1/2_javascript skills
Why do you do this? Is there any basis for this? 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 is translated from "JavaScript Variable Performance published on his personal website on February 10, 2009 by Nicholas C. Zakas 》. The original text is the only official version, and this article is a Simplified Chinese Translation authorized by the original author (Nicholas C. Zakas). The translator (Mingda) has made great efforts to ensure the accuracy of the translation and promises that the content of the translation will be completely faithful to the original text. However, it may still contain omissions and inaccuracies, and you are welcome to correct me. The content of the translation notes is informal and represents only the translator's personal views.
The following is the translation of the original text :
When it comes to how to improve JavaScript performance, the most common suggestion you hear should be to use local variables as much as possible (local variables) instead of global variables (global variables). This is advice that has stuck with me and never questioned it in my nine years of working in web development, and it's based on 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.
First, copy the objects in the internal properties of the function object [[Scope]] to the scope chain in order.
Secondly, when the function is executed, a new Activation Object object will be created, which contains the definition 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, that is, the Global Object, is not found, 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.
첫 번째 테스트는 가장 간단한 값을 변수에 쓰는 것입니다(여기서는 리터럴 값 1이 사용됨). 결과는 아래 그림에 표시되어 있는데, 이는 매우 흥미롭습니다.
결과와 차이 없음 식별자 확인 과정에서 심층 검색이 필요한 경우 성능 손실이 발생하며 식별자의 깊이가 커질수록 성능 손실 정도가 증가한다고 보기 어렵습니다. 당연히 Internet Explorer의 성능이 가장 나빴습니다(그러나 공정하게 말하면 IE 8에서는 약간의 개선이 있었습니다). 여기에는 몇 가지 예외가 있다는 점은 주목할 가치가 있습니다. Google Chrome과 최신 Midnight 버전의 WebKit은 변수에 대한 액세스 시간이 매우 안정적이며 범위 깊이가 증가해도 증가하지 않습니다. 물론 이는 그들이 사용하는 차세대 JavaScript 엔진인 V8 및 SquirrelFish에 기인합니다. 이러한 엔진은 코드를 실행할 때 최적화를 수행하며, 이러한 최적화를 통해 이전보다 더 빠르게 변수에 액세스할 수 있다는 것은 분명합니다. Opera도 IE, Firefox 및 현재 버전의 Safari보다 훨씬 빠르지만 V8 및 Squirrelfish 기반 브라우저보다는 느립니다. Firefox 3.1 Beta 2의 성능은 조금 의외입니다. 로컬 변수의 실행 효율은 매우 높지만, 스코프 레이어 수가 늘어나면서 효율성이 크게 떨어집니다. 여기서는 기본 설정을 사용하고 있는데 이는 Firefox에서 추적 기능이 켜져 있지 않음을 의미합니다.