JS Efficiency personal experience Talk (8-15 update), add range tips _javascript Tips

Source: Internet
Author: User
Tags bind
First of all, thank Csdn hbhbhbhbhb1021 (I want to work hard) and cuixiping (unintentional) reminders. I will take the time to use IE proprietary methods such as: insertAdjacentHTML speed also measured out to see if the appropriate amount of data when IE, without innerhtml speed.
The main test here is not the speed at which data is generated, but the speed at which it is matched.For example
The speed of my match here
I measured 10,000 data, valid data is 1000-1100, output complex HTML, speed is about 360ms, the method is matching match (with loop)
Want to post your test data.
Row innerHTML and insertadjacenthtml speed test, compared to the average result is not greater than 20ms (average speed), in IE insertadjacenthtml speed is very fast, under the Mozilla is not worth the candle.

You can click here for a simple match test
Click here for innerHTML and insertadjacenthtml speed test, which can be compatible with Mozilla's

Write this article, in the meantime I also delete subtract subtract, so the statement also not fluent, see friend also hard some.

This article is mainly out of a friend using my original AutoComplete JS control. When the volume of data, there will be extremely inefficient situation, I have done some of the tests and some experience, and share with you, if the wrong place, please point out.

After testing, we will find the following situation or conclusion, if your test results do not match my, please explain the reasons for each other to learn.

1 trouble occurs when a larger HTML string is given to obj.innerhtml. That is, when a larger string is given an element's innerHTML, the process may be intolerable to us. (and actually it's not JS's fault, but it's really string data too much)
2 The method of flattening the string can improve the efficiency, while the string is larger, 2 is still present. More than a certain amount, the speed will obviously slow down.
3 The regular matching method will be more efficient than the usual method of traversal.
4 during execution, the time to bind the event will be more expensive. Tests are approximately 30 times times more likely to match and generate HTML data in the case of 1w data, which means that the total cost of generating data is 100ms, while binding events require 3000ms.
5) Generally speaking. IE is slower than Mozilla (I'm using a Firefox1.5 test).
6 when large amount of data, do not use DOM to generate element.
7 Non-JS built-in method, may cause a lot of time too much duplication of labor and may be the reverse. It is recommended that the method be built as much as possible.
Summary questions:
First, in the string to the innerHTML.
Second, the time it takes to cycle the binding event.
Third, the generation of the div we need to spend time.
Four, different browser issues.

The following remedies:

Question One

We can do nothing else, only as few HTML strings as possible, such as the most basic one div, can be written like this
<div style= "height:20px; Font:9pt Verdana; " ></div> can also write <div class= "C1" ></div&gt, and the second is significantly faster than the first. If not, please see if the following method is appropriate for you.

In the process of doing the program when suddenly remembered to 51js PK Tree, a moderator written by one of the trees, 1 million of a node, dynamic load. It only takes less than 1 seconds. No doubt, it must be tricky, because as long as the only tree-only HTML is a large number. The special place of this tree is to build the tree, not 1 million of the nodes are generated at once innerHTML, but only generated in the view range of nodes, when the scroll roll downward, only dynamic regeneration into the tree node. This method at least I think is very open, very valuable.

As we know, the MySQL database can be taken from the data. SELECT * FROM table limit 0,100, meaning that only 0-100 of the data in the database is taken. Here may be some friends also think of, in JS, we can use this method to take the data, an array as a table. Just a simple data table, not a two-dimensional table. As shown in figure

Using this, we can take the value of the data valid first. As shown in figure:

Think about it. If we take an array, subscript 10000, set the node to generate a AutoComplete HTML length 20 (already very small "<div class=" "Out" >item</div>).
Matching data is known: There are 3,000 data
The number of bytes in the section is: 3000 (ASC code) is the 3000*20=60000 byte
With the limit method, the output is: 10*20=200 byte.
There's a clear gap!
Then we can solve the problem step-by-step, that is, when the scroll bar appears, or press down (arrow keys) and then dynamically generate innerHTML.
8-13 update: Measured, with their own written limit speed, and the array.slice speed than a moment, the speed is similar, and sometimes even faster than the slice speed.
Array.prototype.limit = function (l, h) {
var _a = this; var ret = [];
L = l<0?0:l; H = h>_a.length?_a.length:h;
for (var i=0; i<_a.length; i++) {
if (i>=l && i<=h) ret[ret.length] = _a[i];
if (i>h) break;
}; return ret;
}
Interested friends can also test their own, paste out the data to see which efficiency is better.

Question Two,
Why do we have to loop to bind events?
Or because of the problem.
Suppose this is written
1)
<div id= "Container" >
<div onclick= "Handlerclick ()" >never-online</div>
</div>
You can also write this
2)
<div id= "Container" >
<div>never-online</div>
</div>
document.getElementById ("container"). Childnodes[0].onclick=function () {Handlerclick ()};
This can also save string resources by eliminating some strings. But also need to container the child elements to iterate, so it will take time, the first method or the second? I suggest you use the first one, but it's best to minimize the string, such as:
<div id= "Container" >
<div onclick= "_c ()" >never-online</div>
</div>
Large amount of data, or fewer characters the better, although the code is not beautiful.

Question three,
We can generate the div when we generate it.
var div = document.createelement ("div");
Div.onclick=function () {};
Todo
You can also use strings like this
var sHtml = "<div onclick=foo () >val</div>";
When the number of hours, the first speed will be faster than the second. But when it reaches an order of magnitude, the second is significantly faster than the first. In general, the second is better. Because the second one can be more flexible, such as the use of join, and a regular match.

Question Four,
This problem cannot be neglected. Each browser has different characteristics, speed implementation is also different, I personally think, this and JS on the optimization efficiency is the same.
Use the built-in methods of the browser itself as much as possible, so that you can improve efficiency in most cases.

So how can you improve the efficiency of your scripts?
1 match with match, a acache array. Loop match.length, give Acache, then use Join ("") and give innerHTML (this method still needs to be cycled, and an extra array is required for temporary data storage)
2 does not need to be cycled, but the specified string must be generated in addition to generating the data. (This method also requires additional space for temporary data) as shown in the figure:

3 It is better to judge multiple times and do not repeat a match again. e.g:
The value that is first fetched in the input control is: 1, and the second time the value is 12
If you make a judgment, you can store a value for the event, which is the value that was pressed the previous time. Like the value 1 above. The second time you press without a backspace, that is, add a character 2 to the previous value, then we will match the data in the previous 1. This can greatly reduce the number of cycles.
4 using the limit written in question one, the data is taken out dynamically. These can be a good solution to the problem of the HTML string too large, but if this method is not controlled properly, it will be the reverse.
5)Use range techniques to join HTMLSTR, that is, when an HTML string is too large, and then use INNERHTML+=ANOTHERHTMLSTR, such a method, also will make the speed too slow, in IE, we can use Obj.insertadjacenthtml ("BeforeEnd", ANOTHERHTMLSTR) Such a method to insert HTML, this method has been tested and relatively stable. Using Limit plus insertadjacenthtml makes the HTML code that is inserted more stable, and in Mozilla, you use range techniques to do this, as follows:
if (Browser.ismozilla) {
HTMLElement.prototype.insertAdjacentHTML = function (Swhere, SHTML) {
var df; var r = This.ownerDocument.createRange ();
Switch (String (swhere). toLowerCase ()) {
Case "Beforebegin":
R.setstartbefore (this);
DF = r.createcontextualfragment (SHTML);
This.parentNode.insertBefore (DF, this);
Break
Case "Afterbegin":
R.selectnodecontents (this);
R.collapse (TRUE);
DF = r.createcontextualfragment (SHTML);
This.insertbefore (DF, this.firstchild);
Break
Case "BeforeEnd":
R.selectnodecontents (this);
R.collapse (FALSE);
DF = r.createcontextualfragment (SHTML);
This.appendchild (DF);
Break
Case "Afterend":
R.setstartafter (this);
DF = r.createcontextualfragment (SHTML);
This.parentNode.insertBefore (DF, this.nextsibling);
Break
}
};
}
PostScript: The efficiency problem does not have a complete solution, only in practice according to the need to decide. Therefore, the above method is for your reference only, if you have some good methods, you can write down your experience in the comments in order to communicate.

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.