Read high performance JavaScript programming Chapter Two let me know why the code is written like this

Source: Internet
Author: User

Why does the code have to write like this?

function Initui () {var doc = document, BD = doc.body, links = doc.getelementsbytagname_r ("A"), I = 0, len = links.length; w Hile (i < len) {update (links[i++]),} doc.getelementbyid ("Go-btn"). onclick = function () {Start ();}; Bd.classname = "active"; }

And not like that?

Avoid
function Initui () {var bd = document.body, links = document.getelementsbytagname_r ("A"), I = 0, len = links.length; while ( I < len) {update (links[i++]);} document.getElementById ("Go-btn"). onclick = function () {Start ();}; Bd.classname = "active"; }

Obviously we all know that the first performance is better than the second one, why?

The first thing you need to know about JS engine data access. This is only a non-optimized JS engine.

1. Access Literal values Direct amount eg: string, number, Boolean, object, array, function, regular expression, null value with special meaning, and undefined.

2. Access Variables variable var creates a value for storing data.

3. Access an array object with a numeric index to the array items .

4. Access object Members have a character index of the JS object .

From the above example, we can also guess that accessing local variables is faster than accessing object members and array items.

So why are access to object members and array items slower? The book is very detailed, I only introduce my own understanding and excerpts.

Most JavaScript code is written in object-oriented form. Whether by creating a custom object or using a built-in object, such as

Objects in the Document Object Model (DOM) and the browser object model (BOM).

Object members include properties and methods, and in JavaScript, they differ very slightly. A named member of an object can contain any data class
Type. Since a function is also an object, an object member can contain a function in addition to the traditional data type. When a named member is cited
When a function is used, it is called a "method", and a non-function type of data is called a "property".

The objects in JavaScript are based on the prototype. Prototype is the basis of other objects, defining and implementing a new object must have a
Rapporteur This concept is completely different from the concept of "class" in traditional object-oriented programming, which defines the process of creating a new object. The prototype object is all
Object instances of a given type are shared, so all instances share the members of the prototype object.

An object is bound to its prototype through an internal property. Firefox,safari, and Chrome opens this property to developers, saying
for __proto__; Other browsers do not allow scripting access to this property. Any time you create an instance of a built-in type, such as Object or
Array, these instances automatically have an Object as their prototype.

Therefore, objects can have two types of members: instance members (also known as "own" members) and prototype members. Instance members exist directly in the
Instance itself, while the prototype member inherits from the object's prototype.

It's hard to understand, but it's very thorough after looking. Immediately following the last sentence, it is certainly quicker to invoke the instance member than to invoke the prototype member, such as

var book = {   title: ' High Performance JavaScript ',   Publisher: ' Yahoo! Press '}; alert (book.tostring ()); Alert ( Book.title);

The book itself is not ToString, but the program compiles without error, because ToString is its prototype member.

Suppose book.title = = = Book.tostring () book.tostring () is still slower than book.title.

After the book is created, its prototype is bound to the internal properties of the _proto_, and it is observed that the prototype can see the ToString () identifier book itself does not have the ToString function

It is inherited from its prototype. In fact, when calling Book.title, how does the JS engine know if the title is undefined?

In the execution of a function, each time a variable is encountered, the identifier identifies/resolves the variables by searching the scope chain of the run-time context in order to find an identifier of the same name, if not found, or undefined.

So usually the return undefined is destined to retrieve the entire scope chain. It is this kind of search that affects performance.

If ToString is more than title in the scope chain then you can determine that the title will be found before ToString.

What is a run-time context and what is a scope chain?

Each JavaScript function is represented as an object. Further, it is a function instance. function objects, like other objects,
Have properties that you can access programmatically, and a series of internal properties that cannot be accessed by the program and used only by the JavaScript engine. One of
The internal property is [[Scope]] and is defined by the ECMA-262 standard third edition.

The internal [Scope] property contains a collection of objects in the scope in which a function is created. This collection is called the function's scope chain and it determines
Which data can be accessed by a function. Each object in the scope chain of this function is referred to as a mutable object, with each mutable object being a "key-value pair"

the form exists . when a function is created, its scope chain is populated with objects that represent accessible in the environment in which this function was created
the data . For example, the following global function:

function Add (NUM1, num2) {
var sum = num1 + num2;
return sum;
}

The figure shows only the position of the global object in the scope chain, and does not include all.

Note: These mutable objects in scope chain (scope chain) exist in the form of key-value pairs.

The activation object in the figure is translated as an active object this object is created when this add function is called, for example: Run this code var s = Add (n);

When you run this code, an internal object is created (previously mentioned, like [[XXX]]) called execution context, which is the run-time context described above. It defines the environment in which a function is run.

It is worth mentioning that each run-time context is unique for each run of the function, so calling the same function multiple times results in creating the runtime contexts multiple times. When the function is executed, the runtime context is destroyed.

The run-time context also has scope chain. This scope chain is used for identifier parsing.

When the run-time context is created, its scope chain is initialized, along with the objects contained in the function's [scope] property, which are copied sequentially into the scope chain of the run-time context. The last thing you see is

activates the object. It is pushed to the front of the scope chain. identifier recognition is a front-to-back.

The end result is that the ToString identifier is located at the back end of the scope and the title identifier is in the front of the scope chain, so ToString will be slower.

Back to the beginning of the topic you will find that you simply cache the document into a local variable doc to reduce the number of very deep identifier scans one or more times.

It is also possible to realize that the deeper the member nesting, the deeper the scan scope chain. The deeper the member nesting, the slower the access speed. Location.href is always faster than window.location.href.

This is somewhat similar to the effect of tail recursion.

The book says in detail that identifier performance, dynamic scope, closures can cause memory leaks, and change the scope chain. As well as the prototype, prototype chain. In short, benefited.

Read high performance JavaScript programming Chapter Two let me know why the code is written like this

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.