This article will briefly discuss the problem of optimizing jQuery code from the perspective of character selection.
Sizzle Running Mechanism
JQuery starts from 1.3 to separate the code for searching elements based on the selector expression, that is, the Sizzle engine. When we put a selector expression (such as "# id ",". when class ",": nth-child (2) ") is passed to the $ () function, Sizzle will first use the native DOM method supported by the browser to find elements, to obtain the maximum execution speed. The following are several standard native methods that Sizzle will prioritize (the usage of each method is not described here ):
Copy codeThe Code is as follows:
GetElementById ()
GetElementsByTagName ()
GetElementsByClassName ()
QuerySelectorAll ()
If the browser does not support a method, or the input selector expression is not a standard selector (for example, ": eq ()", ": odd", or other custom selector ), sizzle will use document. getElementsByTagName ('*') to retrieve all elements in the document, traverse and test each element. Obviously, this is a method that can only be used. It is conceivable that the most stupid method is the lowest efficiency.
Optimization example
For example, assume that we want to retrieve all the text boxes in the page form, that is:
<Input type = "text">
You can use two delimiters:
Copy codeThe Code is as follows:
$ ('Input [type = "text"] ')
$ ('Input: text ')
The first selector is the standard CSS attribute selector, and the second is the custom selector. According to the analysis of the Sizzle engine, in most modern browsers (browsers that support native querySelectorAll () methods), the first selector is much faster than the second one.
Here is another example. Assume there are two jQuery queries:
Copy codeThe Code is as follows:
$ ('Input'). eq (1)
$ ('Input: eq (1 )')
The first query first searches for all input elements using the standard CSS element selector, and then calls the jQuery eq () method to obtain the second element (eq () in the matching result () the index parameters of the method are calculated from 0 ). The second query uses the custom pseudo-class selector eq (). The test shows that the speed of the first method is much faster than that of the second method.
Conclusion
You should try to use the selector specified in the CSS specification. Unless there is no standard selector, jQuery's custom selector should be considered.
(Note: This article is based on the content of the relevant chapter in jQuery basic tutorial (version 3rd .)