Are jQuery's :first and :eq(0) selectors functionally equivalent?

前端 未结 3 1700
礼貌的吻别
礼貌的吻别 2020-12-17 14:27

I\'m not sure whether to use :first or :eq(0) in a selector. I\'m pretty sure that they\'ll always return the same object, but is one speedier than the other?

I\'m

相关标签:
3条回答
  • 2020-12-17 14:55

    2018: Yes, :first and :eq(0) return the same result although the performance difference would be marginal and perhaps even trivial in 2018.

    2010: Good question and great post. I tested this some while ago and couldn't remember the exact outcome. I'm really glad to have found this because it's precisely what I was looking for.

    I would guess that the reason for :first and :eq(0) being a tad slower is most likely related to parsing performance. Omitting these allows the jQuery engine to utilize the native getElementsByTagName and getElementsByClassName functions.

    No surprises i.t.o. the DOM element being the fastest to access. Wrapping the DOM element with jQuery in a for loop won't necessarily have an adverse effect on performance as jQuery makes use of an expando property for caching purposes.

    However, it would be interesting to see how get(0) compares with DOM element access and how the jQuery wrapping thereof fares against eq(0) and the rest of the results.

    0 讨论(0)
  • 2020-12-17 15:11

    According to jQuery's source code, .first() is just a convenience wrapper for .eq(0):

    first: function() {
        return this.eq( 0 );
    },
    
    0 讨论(0)
  • 2020-12-17 15:14

    Yes they are equivalent.

    No they aren't likely to be significantly different (anything else is micro-optimization).

    0 讨论(0)
提交回复
热议问题