Use the best Selector
When using JQuery, you can use multiple selectors to select the same element. The performance of different methods is different. Sometimes the difference is very large. Commonly used selectors include the following:
Based on experience, we should know that the performance of these five selectors is declining in turn. Let's take a test to see how different their performance is:
Test Results
| Solution |
IE6 |
IE7 |
IE8 |
IE9 |
Chrome |
Firefox |
Opera |
Safari |
| $ ("# Mytable td.tar get ") |
5150 |
5630 |
780 |
293 |
69 |
148 |
31 |
102 |
| $ ("# Mytable. target ") |
5320 |
5780 |
940 |
297 |
61 |
141 |
32 |
101 |
| $ ("# Mytable"). find ("td.tar get ") |
4840 |
5000 |
1250 |
387 |
95 |
205 |
73 |
157 |
| $ ("# Mytable"). find (". target ") |
5000 |
5150 |
1400 |
226 |
49 |
130 |
60 |
64 |
| $ ("# Mytable td [target = target]") |
16410 |
17660 |
940 |
406 |
89 |
166 |
35 |
120 |
| $ ("# Mytable td: hidden ") |
25000 |
26720 |
23750 |
3638 |
632 |
1123 |
3434 |
569 |
| $ ("# Target-td ") |
630 |
620 |
310 |
62 |
9 |
28 |
12 |
18 |
| $ (". Target ") |
10310 |
10790 |
940 |
207 |
36 |
181 |
47 |
44 |
| Document. getElementById ("target-td ") |
150 |
150 |
160 |
6 |
1 |
1 |
5 |
2 |
Conclusion
Best practices
Avoid performing global search
=>
Ensure that the query path is the shortest and the performance is the best. Refer to the first article;
Avoid null results
For the selection result with a quantity of 0, JQuery performs the default action and does not report an error, which affects the program performance.
A:
B:
Test Results
| Solution |
IE6 |
IE7 |
IE8 |
IE9 |
Chrome |
Firefox |
Opera |
Safari |
| A |
6110 |
5610 |
1344 |
488 |
103 |
194 |
108 |
155 |
| B |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
Conclusion
Avoid null objects;
Use a style sheet to avoid multiple style adjustments
Apply multiple styles to an object. It is best to use a style sheet to avoid multiple applications.
Test Results
| Solution |
IE6 |
IE7 |
IE8 |
IE9 |
Chrome |
Firefox |
Opera |
Safari |
| A |
2594 |
2486 |
1500 |
501 |
163 |
222 |
190 |
191 |
| B |
1000 |
953 |
547 |
190 |
79 |
28 |
15 |
86 |
| C |
843 |
672 |
407 |
111 |
21 |
17 |
16 |
31 |
Conclusion