Does it make sense to jQuery cache $(this)?

后端 未结 2 1583
清酒与你
清酒与你 2020-12-02 01:27

I\'m still learning about jQuery, but I have not been able to find a solid answer. I know every time you use the jQuery selector $(...) there is a performance

相关标签:
2条回答
  • 2020-12-02 02:05

    If you're using it a lot, yes it makes sense, or chain, e.g.:

    $(this).fadeIn().fadeOut().somethingElse();
    

    If it expensive? No not really in the grand scheme of things...but if you're in a loop the cost multiplies so it's best to cache it. If you're using it more than once it makes sense, how much sense depends on how much performance matters for that bit of code I suppose.

    0 讨论(0)
  • 2020-12-02 02:18

    Good question, Jason. I imagine the jQuery selector function notices the this keyword fairly efficiently. That said, it does make sense to not make repeated calls to the same selector if you can avoid it. This is where method chaining comes in useful:

    $(this).hide().show().hide();
    

    If you're going to use the same selector a lot at different points in the same function, I'd probably make a variable to store the return value of the jQuery selector function. Absent that, I wouldn't worry about it, because it's really a very, very small amount of processing that is done...especially since I'm fairly sure the jQuery library checks for the this keyword (and a string type) before it runs any regular expressions.

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