High-Performance JavaScript (chapter II data Access)

Source: Internet
Author: User

1, the data storage location related to the speed of access. There are four basic data access locations in JavaScript:

Direct Volume:

Variable:

Array:

Object:

2, in most cases, the performance difference between a direct volume and a local variable data access is negligible.

3. Scope and Identifier parsing:

Each JavaScript function is represented as an object. Further, it is a function instance . A function object, like other objects, has properties that you can programmatically access, and a series of internal properties that cannot be accessed by a program and used only by the JavaScript engine.

One of the internal properties is [[Scope]], which is defined by the ECMA-262 standard third edition.

4. The internal [Scope] property contains a collection of objects in the scope to which a function is created. This collection is called the scope chain of the function, and it determines which data can be accessed by the function. Each object in the scope chain of this function is called a mutable object.

  When a function is created, its scope chain is populated with objects that represent the data accessible in the environment in which this function was created. For example, the following global function:
function Add (NUM1, num2) {    var sum = num1 + num2;     return sum;}

When the Add () function is created, it fills a single Mutable object in its scope chain, which represents all global scope-defined variables. This global object contains access interfaces such as Windows, browsers, and documents.

Figure 2-2 shows the relationship between them (note: Only a few of the global variables are drawn in this figure and many others).

  

  

var total = Add (5, 10);

When you run this add function, an internal object is established, called the run-time context. A run-time context defines the environment at which a function runs. Each run-time context is unique for each run of the function, so invoking the same function multiple times results in the creation of a run-time context multiple times. When the function is executed, the runtime context is destroyed.

A run-time context has its own scope chain, which is used for identifier resolution. When the run-time context is created, its scope chain is initialized, along with the objects contained in the [Scope] property of the running function. These values are copied into the scope chain of the run-time context, in the order in which they appear in the function.

Once this work is done, a new object called an " active object " is created for the run-time context. This activation object acts as a mutable object for the execution period of the function, and includes access to all local variables, named parameters, parameter sets, and this interface. This object is then pushed into the front end of the scope chain.

When the scope chain is destroyed, the active object is destroyed together. Figure 2-3 shows the run-time context and its scope chain for the previous instance code.

    

In the process of running a function, the identifier recognition process determines where to obtain or store data for each variable encountered. This search process occurs when a function accesses sum,num1,num2. It is this search process that affects performance.

5. Use local variables to store variable values outside of the local scope, if they are used more than once in the function, look at the following two segments of code:

  before improvement: three references to document, document is a global object. To search for this variable, you must traverse the entire scope chain until it is finally found in the global variable object

function Initui () {    var bd = document.body,            = Document.getelementsbytagname_r ("A"),             = 0,            = links.length;      while (I < len) {        update (links[i+ +]);    }    document.getElementById (function  () {        start ();    };     = "Active";}

  after improvement: the reference to the document is stored in the local variable doc. The number of times to access global variables is now 1, not 3. Replacing document with Doc is faster because it is a local variable, and if the dozens of global variables are repeatedly accessed, performance is sure to be greatly improved.

function Initui () {    var doc = document,            = doc.body,            = Doc.getelementsbytagname_r ("a"),            = 0,            = links.length;      while (I < len) {        update (links[i+ +]);    }    Doc.getelementbyid (function  () {        start ();    };     = "Active";}
   Change scope chain: with
function Initui () {    with//avoid!        var bd = body,                = Getelementsbytagname_r ("A"), I = 0,                = links.length;          while (i < len) {            update (links[i+ +]);        }        getElementById (function  () {            start ();        };         = "Active";}    }

While this prevents the document from being written multiple times, it can cause another problem:

When a code flow executes into a with expression, the scope chain of the run-time context is temporarily changed. A new Mutable object is created that contains all the properties of the specified object.

This object is inserted into the front end of the scope chain, meaning that all local variables of the function are now pushed into the second scope chain object, so the access cost is higher:

  Change action chain field: Try-catch

When an error occurs in a try block, the program flow is automatically transferred to the catch block and the exception object is pushed into a mutable object in the front of the scope chain . In a catch block, all local variables of the function are now placed in the second scope chain object.

Note that the scope chain returns to its original state as long as the catch clause finishes executing.

Of course, if you know that the error will occur, then you should fix the code itself

Handing the error to a dedicated function to handle a temporary change in the scope chain does not affect the performance of the code because there is only one statement and no local variable access.

Try {    catch  (ex) {    handleError (ex);   // delegate to handler method}

6. Dynamic Scope:

A catch clause, whether with an expression or a try-catch expression, and a function that contains () are considered dynamic scopes. A dynamic scope exists only because the code is running, so it is not possible to determine (whether there is a dynamic scope) by static analysis (see the code structure). For example:

function Execute (Code) {    (code);     function subroutine () {        return  window;    }     var // What value is W?};

 The Execute () function looks like a dynamic scope because it uses (). The value of the W variable is related to code. In most cases, W will be equivalent to the global Window object, but consider the following scenario:

Execute ("var window = {};")

In this case, the () creates a local window variable in the Execute () function. So W will be equivalent to this local window variable instead of the global one. So, without running this code there is no way to understand the specifics of the case, the exact meaning of the identifier window cannot be predetermined.

Therefore, it is generally not recommended to use dynamic scopes:

7. Closure, scope, and memory performance

function assignevents () {    var id = "xdi9592";    document.getElementById (function  (event) {        savedocument (id);}    ;}

The assignevents () function specifies an event handling handle for a DOM element. This event handler is a closure that is created when assignevents () executes, and can access the ID variable within its scope . To close the access to the ID variable in this way, you must create a specific scope chain.

Scope and closure diagram for the run-time context:

Because the closure's [Scope] property contains an object reference that is the same as the run-time context scope chain, it can have side effects. Typically, a function's activation object is destroyed with the run-time context. When a closure is involved, the activation object cannot be destroyed.

Because the reference still exists in the [Scope] property of the closure. This means that the closure in the script requires more memory overhead than the non-closure function. In large Web applications, this can be a problem, especially in Internet Explorer.

IE implements DOM objects using non-native JavaScript objects, closures can lead to memory leaks (see Chapter 3rd for more information).

When a closure is executed, a run-time context is created, its scope chain is initialized at the same time as the two same scope chain referenced in [Scope], and a new activation object is created for the closure itself (see).

Note the two identifiers,IDs, and savedocument that are used in closures exist at the location after the first object in the scope chain. This is the main performance concern of closures: you often access identifiers that are outside the range, and each access results in some performance loss.

It is best to use closures carefully in scripts, and memory and running speed are worth paying attention to. However, you can mitigate the effect on the speed of operations by handling suggestions for the extraterritorial variables discussed earlier in this chapter: Place commonly used extraterritorial variables in local variables, and then directly access local variables.

8. Object Members:

The difference between the prototype chain and the action chain:

  The relationship between access time and attribute depth

Location.href is always faster than window.location.href faster than window.location.href.toString ()

See the following two code improvements:Code One:
function Haseitherclass (element, className1, className2) {    return element.classname = = ClassName1 | | Element.classname = = className2;}

Improved:

function Haseitherclass (element, className1, className2) {    var currentclassname =  Element.classname;     return Currentclassname = = ClassName1 | | Currentclassname = = className2;}

Code:

function Toggle (Element) {    if (YAHOO.util.Dom.hasClass (element, "selected")) {        "selected ");         return false ;     Else {        "selected");         return true ;    }}

Improved:

function Toggle (Element) {    var Dom = YAHOO.util.Dom;     if (Dom.hasclass (Element, "selected")) {        "selected");         return false ;     Else {        "selected");         return true ;    }}

Summarize:

In JavaScript, the location of the data store can have a significant impact on the overall performance of the code. There are four types of data access: direct volume, variable, array item, object member. They have different performance considerations.

Direct and local variables are accessed very quickly, and array items and object members take longer.

A local variable is faster than an extraterritorial variable because it is in the first object in the scope chain. The deeper the variable is positioned in the scope chain, the longer it takes to access it. Global variables are always the slowest because they are always the last ring in the scope chain.

Avoid using the with expression because it alters the scope chain of the run-time context. The catch clause of the try-catch expression should be treated with care because it has the same effect.

Nested object members can cause significant performance impact and are used sparingly.

The deeper the position of a property or method in the prototype chain, the slower it is to access it.

In general, you can improve the performance of JavaScript code by storing frequently used object members, array items, and extraterritorial variables in local variables. The local variables are then accessed faster than those of the original variables.

High-Performance JavaScript (chapter II data Access)

Related Article

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.