开发者

jQuery Performance Tuning: Does context always matter?

开发者 https://www.devze.com 2023-01-11 15:53 出处:网络
I\'m being asked if there is a difference between two variations on a theme and I honestly don\'t know the answer.

I'm being asked if there is a difference between two variations on a theme and I honestly don't know the answer.

Given the following two functions:

$("table").each(function(){
    $("td", this).live("hover", function(开发者_开发问答){
        $(this).toggleClass("hover");
    });
});

$("table td").each(function(){
    $(this).live("hover", function(){
        $(this).toggleClass("hover");
    });
});

Does one offer better performance over the other? Why?


Measure. Firebug and IE8 web developer toolbar have profiling capabilities.

At first glance I would be tempted to say the second one as in the first one you're doing another lookup in the each method but as I said, only measuring can give you (more) exact results.


As the others stated, profiling matters, test it, but a probably slightly faster variation would be:

$("td").live("hover", function(){
    $(this).toggleClass("hover");
});

;-)


Like XIII said, measuring is probably the only way to get a good answer.

Here are a couple of comments though:

  • All browsers implement a getElementByTagName and getElementById. This means that selecting an element by tag or by Id is likely to be consistently faster than selecting it by class (for example). Obviously in this case, you're only selecting by tag.

  • In the first example, you're constructing a function for each table that will loop through each td, attaching an event handler. In the second case, you're constructing a function for each td in the document (presumably many more). What this means for performance depends on the javascript engine, but I would guess that the first option is less resource hungry.

0

精彩评论

暂无评论...
验证码 换一张
取 消