High-performance JavaScript-Data Access (2)

Source: Internet
Author: User

Dynamic scopes, whether it is a catch clause of a with expression or a try-catch expression, and a function that contains (), are regarded as dynamic scopes. A dynamic scope only exists because of code running. Therefore, it cannot be determined through static analysis (view the code body) (whether the scope exists ). For example, copy the code function execute (code) {(code); function subroutine () {return window;} var w = subroutine (); // what value is w ?}; The copy code execute () function looks like a dynamic scope because it uses (). The value of the w variable is related to the code. In most cases, w is equivalent to the global variable window object, but consider the following: execute ("var window = {};") in this case, () in execute () the function creates a local window variable, so the w is equivalent to the local window variable instead of the global one. Therefore, there is no way to understand the specific situation without running this code, and the exact meaning of the identifier window cannot be predetermined. Closures, scopes, and memory closures are one of the most powerful aspects of JavaScript. They allow functions to access data out of a local range. The use of closures is everywhere in today's most complex web applications. However, there is a performance impact related to closures. To understand the performance of closures, consider the following example: function assignEvents () {var id = "xdi9592"; document. getElementById ("save-btn "). onclick = function (event) {saveDocument (id) ;};} the assignEvents () function creates an event processing handle for a dom element. The event processing handle is a closure, when assignEvents () is created during execution, you can access the id variable within its range. In this way, access to the id variable is closed and a specific scope chain must be created. When assignEvents () is executed, an activation object is created and contains the appropriate content, including the id variable. It will become the first object in the context scope chain at runtime, and the global object will be the second. When a closure is created, the [[Scope] attribute is initialized with these objects. Because the [[Scope] attribute of a closure contains an object reference that is the same as the context Scope chain in the runtime, side effects may occur. Generally, the activation object of a function is destroyed together with the runtime context. When a closure is involved, the activation object cannot be destroyed, because the reference still exists in the [[Scope] attribute of the closure, which means that the closure in the script is different from the non-closure function, more memory overhead is required. This may be a problem in large Web applications, especially in IE. IE uses non-local JavaScript objects to implement DOM objects, and closures may cause memory leakage. When a closure is executed, a runtime context will be created, and its Scope chain and the two identical scopes referenced in [Scope] will be initialized at the same time, then a new activation object is created for the closure itself. The two identifiers, id and saveDocument used in the main closure, exist in the position after the first object of the scope chain. This is the main performance concern of closures: You often access identifiers out of the scope, which leads to some performance loss. It is best to use the closure with caution in the script. Both the memory and Running Speed deserve attention. Store frequently used foreign variables into local variables, and then directly access local variables. Most JavaScript code of object members is written in Object-Oriented form. Whether you create a custom object or use a built-in object, such as an object in the Document Object Model (DOM) or browser Object Model (BOM. Therefore, there are many object members. Object members include attributes and methods. In JavaScript, there is little difference between the two. A named member of an object can include any data type. Since a function is also an object, in addition to the traditional data type, the object member can also contain a function. When a member uses a function, it is called a "method", while a non-function data is called "attribute ". The access speed of the original object member is slower than that of the direct volume or local variable, and the access to the array item is slower in Some browsers. This is related to the nature of objects in JavaScript. Objects in JavaScript are based on the prototype, and the prototype is the basis of other objects, defining and implementing the members required for a new object. This concept is completely different from the "class" concept in traditional object-oriented programming. It defines the process for creating new objects. A prototype object is shared by an instance of a given type. Therefore, all instances share the members of the prototype object. An object is bound to its original shape through an internal attribute. Firefox, Safari, and Chrome open this attribute to developers, known as _ proto __. other browsers seem to not allow scripts to access this attribute. Any time you create a built-in instance, such as an object or Arrary, these instances automatically own an Object as their prototype. Therefore, an object can have two types of members: instance members ("own" members) and prototype members. Instance members exist directly on the instance itself, while prototype members inherit from the original object. For example, var book = {title: "High Performance JavaScript", publisher: "Yahoo! Press "}; alert (book. toString (); // "[object Object]" if the book object has two instance members: title and publisher, note that it does not define the tostring () interface, however, this interface is called and no error is thrown. The toString () function is a prototype member inherited from the book object. The prototype of a prototype chain object determines the type of an instance. By default, all objects are Object instances and inherit all basic methods. For example, toString (). You can also use the constructor to create another type of prototype. Copy the code function Book (title, publisher) {this. title = title; this. publisher = publisher;} Book. prototype. sayTitle = function () {alert (this. title) ;}; var book1 = new Book ("High Performance JavaScript", "Yahoo! Press "); var book2 = new Book (" JavaScript: The Good Parts "," Yahoo! Press "); alert (book1 instanceof Book); // truealert (book1 instanceof Object); // truebook1.sayTitle (); // "High Performance JavaScript" alert (book1. toString (); // "[object Object]" copy the code Book constructor to create a new Book instance. The original form of book1 (_ proto _) is Book. prototype, and the original form of Book. prototype is Object. This creates a prototype chain. book1 and book2 inherit their members. The main difference is that two Book instances share the same prototype chain. Each instance has its own title and publisher attributes, but other members inherit from the original source. When book1.toString () is called, the search must go deep into the prototype chain to find the object member "toString". The deeper the prototype chain, the slower the search speed. Performance Loss is increased every step of the prototype chain. The process of searching for instance members is heavier than the direct access or local access, so the overhead of traversing the original source chain is increased. Nested members because object members may contain other members, such as the mode of window. location. href, which is not common. Every time a vertex is encountered, the JavaScript engine executes a parsing process on the object member. The deeper the member nesting, the slower the access speed. Location. href is always faster than window. location. href, and later is faster than window. location. href. toString. If these attributes are not the instance attributes of the object, it takes a longer time for the member parsing to search for the original chain on each point. Cached object Member values because all these performance problems are related to object members, avoid using them if possible. More specifically, only object members are used when necessary. For example, there is no reason to read the value of the same object member multiple times in a function: function hasEitherClass (element, className1, className2) {return element. className = className1 | element. className = className2;} element. className is accessed twice. We can store a local variable to eliminate a search process: function hasEitherClass (element, className1, className2) {var currentClassName = element. className; return currentClassName = className1 | currentClassName = className2;} in general, if you want to read the same object multiple times in the same function Property, it is best to save it to a local variable. Replace attributes with local variables to avoid performance overhead caused by extra attribute searches. This is especially important when dealing with nested object members, which have an incredible impact on the running speed. Conclusion 1. In JavaScript, the location of data storage can have an important impact on the overall performance of the Code. There are four types of data access types: Direct variables, variables, array items, and object members. They have different performance considerations. 2. Access to direct variables and local variables is very fast, and it takes a longer time for Array items and object members. 3. Local variables are faster than domain variables because they are located in the first object of the scope chain. The deeper the location of a variable in the scope chain, the longer it takes to access the variable. Global variables are always the slowest, because they are always at the end of the scope chain. 4. Avoid using the with expression because it changes the scope chain of the runtime context. And be careful with the try-catch expression catch clause because it has the same effect. 5. nested object members may have a significant performance impact and should be used as little as possible. 6. The deeper the location of an attribute or method in the prototype chain, the slower the access speed.

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.