search
HomeWeb Front-endJS Tutorialjavascript Use local variables to replace global variables Page 1/2_javascript skills
javascript Use local variables to replace global variables Page 1/2_javascript skillsMay 16, 2016 pm 06:52 PM
javascriptglobal variableslocal variables

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.

  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, 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에서 추적 기능이 켜져 있지 않음을 의미합니다.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools