views:

51

answers:

3

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?

+5  A: 

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.

XIII
A: 

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.

Damovisa
+2  A: 

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

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

;-)

frunsi