Several knowledge _javascript skills to effectively improve JavaScript execution efficiency

Source: Internet
Author: User
Tags eval object model stringbuffer

To provide a fresh, chic user experience, many sites use JavaScript to improve design, validate forms, check browsers, and AJAX requests, cookie operations, and so on, to achieve no refreshing dynamic effects. However, to make a lot of content in the browser rendering, if not handled well, the site performance will be drastically reduced. So it's important to understand how to improve the efficiency of JavaScript execution.

JavaScript functions

In JavaScript, a function is precompiled before it is used. Although there are times when you can use strings instead of functions, each time you execute this JavaScript code, it will be parsed to affect performance.

1. Eval Example

Copy Code code as follows:

Eval (' output= (input * input) ');
Proposed change to:
Eval (new function () {output= (input * input)});

2, settimeout example

Copy Code code as follows:

SetTimeout ("alert (1)", 1000);
Proposed change to:
settimeout (function () {alert (1)}, 1000);

Use a function instead of a string to make sure that the code in the new method is optimized by the JavaScript compiler.

JavaScript scopes

Each scope in the JavaScript scope chain contains several variables. It is important to understand the scope chain so that you can take advantage of it.

Copy Code code as follows:

var Localvar = "global"; Global variables

function Test () {

var Localvar = "local"; Local variables

Local variables
alert (Localvar);

Global variables
alert (This.localvar);

Find document find the global variable if the local variable is not found
var pagename = document.getelementbyid ("pagename");
}

Using local variables is much faster than using global variables, because the farther the scope chain is, the slower the parsing is. The following illustration shows the scope chain structure:

If you have a with or Try-catch statement in your code, the scope chain is more complex, as shown in the following illustration:

JavaScript string

A very performance-affecting function in JavaScript is string concatenation, usually using the + sign to implement the concatenation string. However, early browsers did not optimize such connectivity, resulting in a serious reduction in JavaScript execution efficiency in successive creation and destruction of strings.

Copy Code code as follows:

var txt = "Hello" + "" + "world";

Proposed change to:

Copy Code code as follows:

var o = [];
O.push ("Hello");
O.push ("");
O.push ("World");
var txt = o.join ();

Let's simply encapsulate:

Copy Code code as follows:

function StringBuffer (str) {
var arr = [];
Arr.push (str | | "");
This.append = function (str) {
Arr.push (str);
return this;
};
this.tostring = function () {
Return Arr.join ("");
};
};

And then invoke this child:

Copy Code code as follows:

var txt = new StringBuffer ();
Txt.append ("Hello");
Txt.append ("");
Txt.append ("World");
Alert (txt.tostring ());

JavaScript DOM Operations

The HTML document Object Model (DOM) defines a standard way to access and manipulate HTML documents. It represents an HTML document as a node tree that contains elements, attributes, and textual content. You can access all nodes in an HTML document and manipulate them by using HTML dom,javascript.

Dom Redraw

Every time a DOM object modified to a page involves a DOM redraw, the browser renders the page again. So reducing the number of changes to the DOM object can effectively improve the performance of JavaScript.

Copy Code code as follows:

for (var i = 0; i < 1000; i++) {
var elmt = document.createelement (' P ');
elmt.innerhtml = i;
Document.body.appendChild (ELMT);
}

Proposed change to:

Copy Code code as follows:

var html = [];
for (var i = 0; i < 1000; i++) {
Html.push (' <p> ' + i + ' </p> ');
}
Document.body.innerHTML = Html.join (");

Dom Access

Each node in an HTML document can be accessed through the DOM. Each call to getElementById (), getElementsByTagName (), and so on, will find and access the node again. So caching a lookup DOM node can also improve the performance of JavaScript.

Copy Code code as follows:

document.getElementById ("P2"). Style.color = "Blue";
document.getElementById ("P2"). style.fontfamily = "Arial";
document.getElementById ("P2"). Style.fontsize = "larger";

Proposed change to:

Copy Code code as follows:

var elmt = document.getElementById ("P2");
Elmt.style.color = "Blue";
elmt.style.fontFamily = "Arial";
Elmt.style.fontSize = "larger";

DOM Traversal

DOM traversal child elements usually read the next child element sequentially by index, which is inefficient in early browsers, and can improve the efficiency of JS traversal dom by using nextsibling method.

Copy Code code as follows:

var html = [];
var x = document.getElementsByTagName ("P");//ALL nodes
for (var i = 0; i < x.length; i++) {
Todo
}

Proposed change to:

Copy Code code as follows:

var html = [];
var x = document.getElementById ("div");//Parent node
var node = X.firstchild;
while (node!= null) {
Todo
node = node.nextsibling;
}

JavaScript Memory Release

In Web applications, memory consumption becomes larger as the number of DOM objects increases. So the object's reference should be released in time to allow the browser to reclaim the memory.

Freeing the memory occupied by the DOM

Copy Code code as follows:

document.getElementById ("Test"). InnerHTML = "";

Sets the DOM element's innerHTML to an empty string, freeing the memory occupied by its child elements.

Releasing a JavaScript object

Copy Code code as follows:

Object:
obj = null
Object properties:
Delete Obj.property
Array element:
Arr.splice (0,3)//delete the first 3 elements

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.