jquery, performance-wise what is faster getElementById or jquery selector?

后端 未结 8 1204
忘掉有多难
忘掉有多难 2020-12-04 15:45

What is better from performance wise document.getElementById(\'elementId\') or $(\'#elementId\') ? How can I calculate the speed by myself?

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 16:01

    Since the other performance test that was linked in this page seemed to be broken, and it also included something that wasn't asked about in this question (namely a custom jQuery method), then I decided to make a new performance benchmark to answer the question which includes the exact equivalent (returns the DOM element) in jQuery, instead of a custom method:

    https://jsperf.com/jquery-get-0-vs-get-element-by-id

    When I run it in my Chrome, it shows that a straight jQuery

    $('#foo').get(0) 
    

    is 92% slower than the equivalent operation in standard JavaScript

    document.getElementById('foo')
    

    I also tried out what is currently marked as the accepted answer here, which supposedly "much much faster" but it is still 89% slower than the standard JavaScript equivalent:

    $( document.getElementById("foo") ).get(0);
    

    Feel free to run it for yourself and see what you get in your browser, with the performance benchmark that I made. The version with no jQuery seems to be a lot faster.

提交回复
热议问题