


In JavaScript, why should you use local variables whenever possible? _javascript skills
不这么做,对性能到底能带来多大的损失?本文就来探讨这些问题的答案,从根本上了解变量的读写性能都和哪些因素有关。
本文译自Nicholas C. Zakas于2009年2月10日在个人网站上发表的《JavaScript Variable Performance》。原文是唯一的正式版,本文是经过原作者(Nicholas C. Zakas)授权的简体中文翻译版(Simplified Chinese Translation)。译者(明达)在翻译的准确性上做了大量的努力,并承诺译文的内容完全忠于原文,但可能还是包含疏漏和不妥之处,欢迎大家指正。译注的内容是非正式的,仅代表译者个人观点。
以下是对原文的翻译:
在如何提高JavaScript性能这个问题上,大家最常听到的建议应该就是尽量使用局部变量(local variables)来代替全局变量(global variables)。在我从事Web开发工作的九年时间里,这条建议始终萦绕在我的耳边,并且从来没有质疑过,而这条建议的基础,则来自于 JavaScript处理作用域(scoping)和标识符解析(identifier resolution)的方法。
首先我们要明确,函数在JavaScript中具体表现为对象,创建一个函数的过程,其实也就是创建一个对象的过程。每个函数对象都有一个叫做 [[Scope]]的内部属性,这个内部属性包含创建函数时的作用域信息。实际上,[[Scope]]属性对应的是一个对象(Variable Objects)列表,列表中的对象是可以从函数内部访问的。比如说我们建立一个全局函数A,那么A的[[Scope]]内部属性中只包含一个全局对象(Global Object),而如果我们在A中创建一个新的函数B,那么B的[[Scope]]属性中就包含两个对象,函数A的Activation Object对象在前面,全局对象(Global Object)排在后面。
当一个函数被执行的时候,会自动创建一个可以执行的对象(Execution Object),并同时绑定一个作用域链(Scope Chain)。作用域链会通过下面两个步骤来建立,用于进行标识符解析。
1. 首先将函数对象[[Scope]]内部属性中的对象,按顺序复制到作用域链中。
2. 其次,在函数执行时,会创建一个新的Activation Object对象,这个对象中包含了this、参数(arguments)、局部变量(包括命名的参数)的定义,这个Activation Object对象会被置于作用域链的最前面。
在执行JavaScript代码的过程中,当遇到一个标识符,就会根据标识符的名称,在执行上下文(Execution Context)的作用域链中进行搜索。从作用域链的第一个对象(该函数的Activation Object对象)开始,如果没有找到,就搜索作用域链中的下一个对象,如此往复,直到找到了标识符的定义。如果在搜索完作用域中的最后一个对象,也就是全局对象(Global Object)以后也没有找到,则会抛出一个错误,提示用户该变量未定义(undefined)。这是在ECMA-262标准中描述的函数执行模型和标识符解析(Identifier Resolution)的过程,事实证明,大部分的JavaScript引擎确实也是这样实现的。需要注意的是,ECMA-262并没有强制要求采用这种结构,只是对这部分功能加以描述而已。
了解标识符解析(Identifier Resolution)的过程以后,我们就能明白为什么局部变量的解析速度要比其他作用域的变量快,主要是由于搜索过程被大幅缩短了。但是,具体会快多少呢?为了回答这个问题,我模拟了一系列的测试,来测试不同作用域深度中变量的性能。
第一个测试是向一个变量中写入一个最简单的值(这里使用字面量的数值1),结果如下图显示,很有趣:
从结果中不难看出,当标识符解析的过程需要进行深度搜索时,会伴随性能损失,而且性能损失的程度会随着标识符深度的增加而递增。意料之中的是,Internet Explorer表现的是最差的(但公平的说,IE 8还是有一些改善的)。值得注意的是,这里有一些例外情况,Google Chrome和最新的WebKit午夜版在访问变量的时间保持得很稳定,不会随着作用域深度的递增而增长。当然,这应该归功于它们所使用的下一代 JavaScript引擎,V8和SquirrelFish。这些引擎在执行代码时进行了优化,而且很明显,这些优化使访问变量的速度比以往更快。 Opera表现的也很不错,比IE、Firefox和当前版本的Safari要快的多,但比基于V8和Squirrelfish的浏览器要慢。 Firefox 3.1 Beta 2的表现有点出人意料,对于局部变量执行的效率非常高,但随着作用域层数的增加,效率便大打折扣。需要注意的是,我这里使用的都是默认设置,也就是说 Firefox是没有开启Trace功能的。
上面的结果是通过对变量执行写操作而得出的,其实我很好奇,读取变量时的情况会不会有什么不同,于是接着做了下面的测试。结果发现,读的速度要比写的速度快一些,但是性能变化的趋势是一致的。
和上个测试一样,Internet Explorer和Firefox还是最慢的,Opera表现了非常抢眼的性能,而同样的,Chrome和最新版本的Webkit午夜版显示了和作用域深度无关的性能趋势,同样需要注意的是,Firefox 3.1 Beta 2的变量访问时间还是会伴随着深度出现一个奇怪的跳跃。
在测试的过程中,我发现一个有趣的现象,就是Chrome在访问全局变量的时候会有额外的性能损失。访问全局变量的时间和作用域层数没有关系,但是会比访问同样层数的局部变量的时间多出50%。
这两个测试可以给我们带来什么启示呢?首先是验证了那个古老的观点,就是要尽可能的使用局部变量。在所有的浏览器下,访问局部变量都比访问跨作用域的变量要快,当然也包括全局变量。下面这几点应该是通过这个测试得出的经验吧:
* 仔细检查函数中所有使用的变量,如果有一个变量不是当前作用域定义的,而且使用了不止一次,那么我们就应该把这个变量保存在局部变量中,而使用这个局部变量来进行读写操作。这样可以帮助我们将作用域外的变量的搜索深度减少到1.这对全局变量尤为重要,因为全局变量总是被放到作用域链的最后位置来搜索。
* 避免使用with语句。因为它会修改执行上下文(Execution Context)的作用域链,在最前面添加一个对象(Variable Object)。这就意味着在执行with的过程中,实际上的局部变量都被移到作用域链上的第二个位置,这会带来性能上的损失。
* 如果你确定一段代码肯定会抛出异常,那么就要避免使用try-catch,因为catch分支在作用域链上的处理方法和with是一样的。但try分支的代码是没有性能损失的,所以还是建议用try-catch来捕获那些不可预知的错误。
如果你想围绕这个话题展开更多的讨论,我在上个月的Mountain View JavaScript Meetup中曾经发表了一个小演讲。可以在SlideShare上下载幻灯片,或者观看聚会的完整视频,我的演讲大概从11分钟左右时开始。
译者笔记
大家如果在阅读本文的过程中,有什么疑惑,建议延伸阅读以下两篇文章:
* Richie写的《JavaScript对象模型-执行模型》
* 《ECMA-262第三版》,主要看看第十章,就是执行上下文(Execution Context)那张,本文提到的名词在那里都有详细的解释。
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The difference between C++ local variables and global variables: Visibility: Local variables are limited to the defining function, while global variables are visible throughout the program. Memory allocation: local variables are allocated on the stack, while global variables are allocated in the global data area. Scope: Local variables are within a function, while global variables are throughout the program. Initialization: Local variables are initialized when a function is called, while global variables are initialized when the program starts. Recreation: Local variables are recreated on every function call, while global variables are created only when the program starts.

C++ is an object-oriented programming language, and its flexibility and power often provide programmers with great help. However, precisely because of its flexibility, it is difficult to avoid various small errors when programming. One of the most common mistakes is that when a function returns a pointer or reference, it cannot return a local variable or temporary object. So how to deal with this problem? This article will introduce the relevant content in detail. The cause of the problem is that in the C++ language, local variables and temporary objects are dynamically allocated during the running of the function. When the function ends, these local variables and temporary

Golang is a strongly typed programming language with features such as efficiency, simplicity, and concurrency, so it is gradually favored by more and more developers. In the development of Golang, the global variables and local variables of functions often involve data competition issues. This article will analyze the data competition problem of global variables and local variables in Golang functions from the perspective of actual coding. 1. Data competition for global variables Golang global variables can be accessed in all functions, so if rigorous design and coding are not carried out

Local variable type inference in Java10: How to use the var keyword to simplify code Introduction: In Java10, the feature of local variable type inference is introduced. By using the var keyword, the code writing process can be simplified. This article will introduce the use of the var keyword and demonstrate its effect of simplifying the code through sample code. 1. What is local variable type inference? Local variable type inference means that when declaring local variables, you can use the var keyword instead of explicit type declaration. The compiler will express

Local variable type inference in Java10: How to use var keyword in foreach loop Introduction: Java10 is an important version after Java9, which introduces many new features and improvements. One of the highly anticipated features is local variable type inference. In Java10, we can use the var keyword to declare local variables and let the compiler automatically infer the variable type based on the expression on the right. In this article, we will explore how to use

Local variables can be declared within methods, codeblocks, constructors, etc. in Java. Local variables are created when program control enters a method, code block, constructor, etc., and are destroyed when program control leaves a method, code block, constructor, etc. In Java, local variables have no default value. This means that they can be declared and assigned before the variable is used for the first time, otherwise, the compiler will throw an error. Example publicclassLocalVariableTest{ publicvoidprint(){ &am

Local variable type inference in Java10: How to use the var keyword in lambda expressions Introduction: Java10 introduces a new feature of local variable type inference, which allows us to use the var keyword to infer the type of a local variable when declaring it. While this feature may not be necessary in most cases, in some cases it can improve code readability and simplicity. This article will focus on how to use the var keyword in lambda expressions to implement local variable type inference.

Local variable type inference in Java10: How to use finalvar keyword in switch statement As the Java language continues to evolve, each new version introduces some new features and improvements. In Java10, one of the important new features is local variable type inference. This feature allows developers to use the var keyword instead of explicit type declarations, making the code more streamlined and readable. This article will explore how to use the finalvar switch in a switch statement.
