Why is jQuery selector function so slow compared to native DOM methods

后端 未结 3 1837
既然无缘
既然无缘 2020-12-31 08:01

I know this topic has been debated in general several times already, but I am looking for a more technical and detailed insight to understand what is really going on.

<
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 08:38

    There is nothing that jQuery can do as fast as native javascript and that is for a reason: it works hard to make your code cross-browser compliant and easy-to-use. It builds a jQuery object out of most method calls. In that matter, jQuery will be a lot slower than the smallest datapath required because it wants to offer features that are ready to use.

    Let's compare these two "similar" calls:

    document.getElementById("box"): Native method that does a simple lookup operation at a lower level than JavaScript. It then returns the DOM element that is already loaded in memory. This is one of the fastest methods.

    $('#box'): Here, jQuery will begin with some parsing over what you ask it to do. For example, it will validate that it is a well-formed selector, then try to recognize what type of selector it is. Once it's done with the validation, it will try to get the element with ID "box". After then, he will create a new jQuery object, filling it with every expected attribute and making sure that all the browsers (and older browsers too) are getting the same results. This includes a lot of fallbacks and compliance tests. When the object is ready-to-use, you get the element with ID "box". Not as straightforward as getElementById(). When jQuery features aren't required on the targeted element, many would prefer to use getElementById('box') instead of $('#box').


    UPDATE - 15/02/17:

    With jQuery >= 2.0 having no more support for the infamous IE 6/7/8, some compatibility tests aren't needed anymore, making jQuery lighter and faster. Overall performance can be improved by using jQuery >= 2.0 instead of 1.x if you don't need to support older browsers.

提交回复
热议问题