Which has better performance (this) or entire object?

var xyz = document.getElementById("item");
$(xyz).click(function (){
    $(xyz).fadeOut();
});

Or:

var xyz = document.getElementById("item");
$(xyz).click(function (){
    $(this).fadeOut();
});

Which would perform faster?

I can try this:

But it returns 2 milliseconds, which is time to initialize the code, not to run it.

You will waste more time on deciding which technique to use, than will ever be lost from the difference in the code.

A more important consideration is to have the code as easily understandable by people reading the code.

With that in mind, the second sample of code has less duplication, making it the preferred choice.

Possibly an even better solution is to separate out the function, which helps to make it even more clear what’s going on.

function fadeOut() {
    $(this).fadeOut();
}
var xyz = document.getElementById("item");
$(xyz).click(fadeOut);

But then, if the function is only being used once, we could define it inline instead, with:

var xyz = document.getElementById("item");
$(xyz).on('click', function fadeOut() {
    $(this).fadeOut();
});

If you get to the point of using the this keyword several times, that’s when it then becomes beneficial to cache the term to a local variable:

var xyz = document.getElementById("item");
$(xyz).on('click', function doSeveralThingsToItem() {
    var item = $(this);
    item.fadeOut();
    // and other stuff with item below too
});
1 Like

Hi there Webkitnote,

have you not considered using CSS as a preferable option?

Why use a “framework sledgehammer” when a modicum of
CSS will suffice?

[code]

untitled document #inputo:focus { outline:none; border-color:transparent; transition:0.25s ease-in-out; } [/code]

coothead

2 Likes

Great idea. However, this does not apply to my situation, I merely fadeOut() the item for purposes of demo, so you can see what I mean. I actually do NEED the object selected for future processing by JavaScript which is not fadeOut()

I do understand the confusion and I’m sorry for having your time used :frowning:.

It will be less of a waste if you tell us what you actually do need, for the techniques used vary depending on the situation.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.