2

I just want to make sure I understand this basic idea correctly, and no matter how I phrase it, I'm not coming up with completely relevant search results.

This is faster:

function () {
    $('#someID').someMethod( $('#someOtherID').data('some-data') );
}

than this:

function () {
    var variableOne = $('#someID'),
        variableTwo = $('#someIDsomeOtherID').data('some-data');
    variableOne.someMethod( variableTwo );
}

is that correct?

I think the question may be "Is declaring variables slower than not declaring variables?" :facepalm:

The particular case where I questioned this is running a similarly constructed function after an AJAX call where some events must be delegated on to the newly loaded elements.

2
  • 4
    In 99% you wont see a difference. In the remaining 1% the optimizer will probably take care of it. Commented Jun 23, 2016 at 11:22
  • 1
    As Sirko said, these kind of performance boosts are negligible. Code readability should be the focus of attention in these cases. Commented Jun 23, 2016 at 11:29

2 Answers 2

2

The answer you will benefit from the most is It does not make a difference.

Declaring variables and storing data in them is something you do so that you do not have to query that data more than once. Besides this obvious point, using variables rather than chaining everything into one big expression improves readability and makes your code more manageable.

When it comes to performance, I can't think of any scenario where you should debate declaring a variable or not. If there's even an absolute difference in speed, it would be so small that you should not see this as a reason to not use that variable and just leaving your code to becoming spaghetti.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to use the element $('#someID') again and again Then decelaring variable would be useful and caching $('#someId') is recommended.

var x = $('#someId')'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.