chuckfinley
chuckfinley

Reputation: 2595

Which is faster / more efficient?

Which one of the following is faster / more efficient / less memory intensive?

This:

$("#my-div").responsiveSlides({
    auto: true,
    pager: true,
    pause:true,
    nav: false,
    timeout: 3000,
    speed: 500,
    maxwidth: 482,
    namespace: "transparent-btns"
});

Or this:

$target = $("#my-div");
if ($target.length !== 0) {

    $target.responsiveSlides({
        auto: true,
        pager: true,
        pause:true,
        nav: false,
        timeout: 3000,
        speed: 500,
        maxwidth: 482,
        namespace: "transparent-btns"
    });

}

Upvotes: 1

Views: 68

Answers (1)

raina77ow
raina77ow

Reputation: 106375

The first snippet...

  • looks for DOM element with specified ID, wrap the results in jQuery object
  • calls the plugin on that object, passing it as plugin's context (this)
  • if the plugin doesn't store reference to that jQuery object in some inner variable that is exposed to the outer world via functions, discards it (as it's no longer referenced by anything)

Now, if plugin is written correctly, it process its element via this.each or similar mechanism. That means an empty jQuery object will be processed instantly.

The second snippet does the same with two additional things:

  • stores the jQuery object in a variable (so it'll be discarded only when the variable goes out of scope, no matter how plugin is written)
  • checks the jQuery object length

The latter, as I said, is most probably a redundant check. And the former is useful when you're going to reuse this element later. Otherwise the first snippet should be considered an optimal solution, even though it will barely matter in an application of any meaningful scale.

Upvotes: 2

Related Questions