Explore JavaScript Execution Efficiency Issues _ basics

Source: Internet
Author: User
Tags closure eval

JavaScript is a very flexible language, we can arbitrarily write various styles of code, different styles of code will also inevitably lead to the difference in the implementation efficiency, the development process of sporadic access to a number of methods to improve code performance, sorting out the usual and easy to avoid problems

 JavaScript self execution efficiency
JavaScript in the scope chain, closures, prototype inheritance, Eval and other features, in providing a variety of magical functions, but also bring a variety of efficiency problems, with the careless will lead to inefficient implementation.

  1. Global Import
We use some global variables (window,document, custom global variables, and so on) in the coding process, and people who understand the JavaScript scope chain know that Accessing global variables in a local scope requires a layer-by-layer traversal of the entire scope chain up to the top-level scope, while local variables are faster and more efficient, so when you use some global objects in a local scope, you can import them into a local scope, for example:

Copy Code code as follows:

1, as a parameter incoming module
(function (window,$) {
var xxx = window.xxx;
$ ("#xxx1"). XXX ();
$ ("#xxx2"). XXX ();
}) (Window,jquery);

2, staging to local variables
function () {
var doc = document;
var global = Window.global;
}

  2, Eval and class eval issues
we all know that eval can perform the processing of a string as a JS code, and it is said that the code executed using eval is 100 times times slower than the code that does not use eval (specific efficiency I did not test, interested students can test)

JavaScript code performs a "precompiled" operation before execution: first, it creates an active object in the current execution environment and sets the variables declared with Var to the properties of the active object, but at this point the variables are assigned to undefined, and those values are The defined functions are also added as properties of the active object, and their values are exactly the definition of the function. However, if you use "eval", the Code in eval (which is actually a string) cannot be identified in advance and cannot be resolved and optimized in advance, that is, the precompiled operation cannot be performed. Therefore, its performance will be greatly reduced

In fact, now people generally rarely use eval, here I want to say is two class eval scene (new Function{},settimeout,setinterver)

Copy Code code as follows:

Settimtout ("alert (1)", 1000);
Setinterver ("alert (1)", 1000);
(New Function ("alert (1)")) ();

These types of code perform less efficiently, so it is recommended that you directly pass in an anonymous method, or a reference to the method, to the SetTimeout method

  3, the closure after the end of the release of the variable is no longer referenced

Copy Code code as follows:

var f = (function () {
var a = {name: "Var3"};
var b = ["Var1", "var2"];
var c = document.getelementbytagname ("Li");
Other variables
Some operations
var res = function () {
alert (a.name);
}
return res;
})()

The return value of variable F in the above code is the method res returned in a closure consisting of an immediate execution function. The variable retains a reference to all the variables (A,B,C, etc.) in the closure, so the two variables reside in the memory space, especially for the reference to the DOM element, which consumes a lot of memory. And we use only the value of a variable in res, so we can release the other variables before the closure returns.

Copy Code code as follows:

var f = (function () {
var a = {name: "Var3"};
var b = ["Var1", "var2"];
var c = document.getelementbytagname ("Li");
Other variables
Some operations
Release a variable that is no longer in use before the closure returns
b = c = null;
var res = function () {
alert (a.name);
}
return res;
})()

 The efficiency of JS Operation Dom
In the Web development process, front-end execution efficiency bottlenecks are often on the DOM operation, Dom operation is a very performance-consuming thing, how can you try to save performance in the DOM operation process?

1. Reduce reflow
What is Reflow?
When a property of a DOM element changes (such as color), the browser notifies the render that the corresponding element is being redefined, a process called repaint.

If the change involves an element layout (such as width), the browser discards the original attribute, recalculates and passes the result to render to recreate the page element, a process called reflow.

Ways to reduce reflow
First remove the elements from the document, complete the changes and then put the elements back to the original position (when a large number of reflow operations on an element and its child elements, 1, 22 methods of effect will be more obvious)
Set the display of the element to "none", complete the modification, and then change the display to the original value
Define a class class instead of modifying the style property multiple times when modifying multiple style properties (for certain recommended)
Use documentfragment when adding elements to a page
For example

Copy Code code as follows:

for (Var i=0;i<100:i++) {

var child = docuemnt.createelement ("Li");

child.innerhtml = "Child";

document.getElementById ("parent"). AppendChild (child);

}



When you need to access the element's state information more than once in your code, we can save it to a variable when the state is unchanged, which avoids the overhead of having multiple accesses to the DOM, typically:

When looking up DOM elements, try to avoid large-area traversal of page elements, use precise selectors, or specify context to narrow the lookup range, for example, jquery

Selectors with less fuzzy matching: For example, $ ("[name*= ' _fix ']"), multiple selectors ("li.active"), such as IDs and progressively narrowing ranges, etc.
Specify context: For example $ ("#parent. Class"), $ (". Class", $el), and so on

4. Use Event Delegation
Usage Scenario: A list with a large number of records, each record needs to be tied to the event, after the mouse clicks to implement some functions, our usual practice is to each record is bound to listen to events, this practice will lead to a large number of page event listeners, inefficient.

Rationale: We all know that events in the DOM specification are bubbling, meaning that events for any one element will bubble up to the top of the DOM tree as they are not actively blocking event bubbling. The event object also provides Event.target (ie, srcelement) to the source, so even if we listen to the event on the parent element, we can find the most primitive element that triggers the event, which is the basic principle of the delegate. Nonsense not much to say that on the example

Based on the principle of the listening event described above, let's rewrite it.

Of course, we do not have to do every time the source of the judgment work, you can abstract it to the tool class to complete. The delegate () method in jquery implements the feature

The syntax is such as $ (selector). Delegate (Childselector,event,data,function), for example:

Copy Code code as follows:

$ ("div"). Delegate ("button", "click", Function () {
$ ("P"). Slidetoggle ();
});

Parameter description (quoted W3school)
parameter   description
childselector  required. Specify one or more child elements to attach an event handler to.
event  required. Specify one or more events that are attached to an element. Multiple event values are separated by a space. Must be a valid event.
data  Optional. Specify additional data to be passed to the function.
function  required. Specify the function to run when an event occurs.
Tips: Event delegates also have the advantage that events that are triggered on elements that are dynamically added after an event binding can also be heard, so that you don't have to bind events to them every time you dynamically add elements to the page

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.