High-performance JavaScript DOM programming

Source: Internet
Author: User

Transfer from (for learning)

Han Zi late

Website: http://www.cnblogs.com/zichi/p/4713031.html

We know that DOM is an application interface for manipulating XML and HTML documents, and that scripting DOM operations is costly. There is an apt analogy, the DOM and JavaScript (here refers to ecmscript) respectively imagined as an island, they are connected with a toll bridge, ECMAScript each access to the DOM, to the bridge, and pay "bridge fee", access to the DOM more times, The higher the cost. Therefore, the recommended practice is to minimize the number of crossings, and strive to stay on ECMAScript Island. We can't use the DOM interface, so how can we improve the efficiency of our programs?

1. Dom Access and modification

There is a cost to accessing the DOM element ("Bridge fee" you know), the cost of modifying the element is more expensive, because it causes the browser to recalculate the geometry of the page (rearrange and redraw).

Of course the worst case is to access or modify the element in the loop, and look at the following two sections of code:

var times = 15000;

Code1

Console.time (1);

for (var i = 0; I < times; i++) {

document.getElementById (' MyDiv1 '). InnerHTML + = ' a ';

}

Console.timeend (1);

Code2

Console.time (2);

var str = ';

for (var i = 0; I < times; i++) {

str + = ' a ';

}

document.getElementById (' MyDiv2 '). InnerHTML = str;

Console.timeend (2);

The results of the first run of the time is actually the second thousand times! (Chrome version 44.0.2403.130 m)

1:2846.700ms

2:1.046ms

The problem with the first piece of code is that every iteration of the loop, the element is accessed two times: Read the value of innerHTML one time, rewrite it again, that is, each loop is crossing the bridge (Reflow and redraw will be explained in the next article)! The result is a good indication that the more times the DOM is accessed, the slower the code runs. As a result, you can reduce the number of DOM accesses as much as possible and stay on the ECMAScript side of the process.

2. HTML Collection & Traversal DOM

Manipulating the DOM another energy point is to traverse the DOM, generally we will collect an HTML collection, such as with getElementsByTagName (), or with document.links, etc., I think everyone is not strange. The result of the collection is an array-like collection that is in real-time presence in a "real-time state," meaning that it is updated automatically when the underlying document object is updated. What do you say? It's very easy to give a chestnut:

<body>

<ul id= ' fruit ' >

<li> Apple </li>

<li> Orange </li>

<li> Banana </li>

</ul>

</body>

<script type= "Text/javascript" >

var lis = document.getelementsbytagname (' li ');

var peach = document.createelement (' li ');

peach.innerhtml = ' peach ';

document.getElementById (' fruit '). appendchild (Peach);

Console.log (lis.length); 4

</script>

And this is the source of inefficiency! Quite simply, as with array optimizations, caching a length variable is ok (reading the length of a collection is much slower than reading a lengh of an ordinary array, because it is queried every time):

Console.time (0);

var lis0 = document.getelementsbytagname (' li ');

var str0 = ';

for (var i = 0; i < lis0.length; i++) {

STR0 + = lis0[i].innerhtml;

}

Console.timeend (0);

Console.time (1);

var lis1 = document.getelementsbytagname (' li ');

var str1 = ';

for (var i = 0, len = lis1.length; i < Len; i++) {

STR1 + = lis1[i].innerhtml;

}

Console.timeend (1);

Let's see how much performance improvement can be.

0:0.974ms

1:0.664ms

When the length of the set is large (the demo is 1000), the performance improvement is obvious.

High-performance JavaScript proposes another optimization strategy, which states that "because traversing an array is faster than traversing the set, if you copy the collection element to the array first, then the properties of the access it will be faster", tested, and did not find this law well, so do not superfluous, The test code is as follows: (There is doubt welcome to discuss with me)

Console.time (1);

var lis1 = document.getelementsbytagname (' li ');

var str1 = ';

for (var i = 0, len = lis1.length; i < Len; i++) {

STR1 + = lis1[i].innerhtml;

}

Console.timeend (1);

Console.time (2);

var lis2 = document.getelementsbytagname (' li ');

var a = [];

for (var i = 0, len = lis2.length; i < Len; i++)

A[i] = Lis2[i];

var str2 = ';

for (var i = 0, len = a.length; i < Len; i++) {

STR2 + = a[i].innerhtml;

}

Console.timeend (2);

At the end of this section, two native Dom methods, Queryselector () and Queryselectorall (), are believed to be unfamiliar, with the former returning an array (note that their return values do not change as dynamically as the HTML collection), which returns the first element that matches. Well, not all the time it's performance is better than the former HTML collection traversal.

Console.time (1);

var lis1 = document.getelementsbytagname (' li ');

Console.timeend (1);

Console.time (2);

var lis2 = document.queryselectorall (' li ');

Console.timeend (2);

1:0.038ms

2:3.957ms

But because it is similar to CSS selection method, so in the combination of choice, the efficiency will be improved, and convenient. For example, do the following combination query:

var elements = Document.queryselectorall (' #menu a ');

var elements = Document.queryselectorall (' div.warning, Div.notice ');

High-performance JavaScript DOM programming

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.