1

I am pondering this:

function outer()
{
 var myVar = 1;
 function inner()
 {
 alert(myVar);
 }
}

Now, as I understand it, this will result two lookups for the variable - one lookup to check the local variables in the inner function and one lookup for the outer function - at which point the variable is found.

The question is - will this be a particularly large drain on performance when compared to this:

function myFunc ()
{
 var myVar = 1;
 alert(myVar);
}

Which would only require the one lookup for the variable - it's then found as a local variable.

Andrew Whitaker
126k32 gold badges296 silver badges308 bronze badges
asked Apr 20, 2013 at 22:34
5
  • 3
    You never call the inner function. Also, no, it will not be a large drain on performance. Commented Apr 20, 2013 at 22:36
  • Have you identified this code as a performance bottleneck? If not, write the one that makes the most sense from a maintainability/code organization standpoint. Commented Apr 20, 2013 at 22:38
  • @AndrewWhitaker: Obvious answer is obvious. Commented Apr 20, 2013 at 22:40
  • 3
    Don't underestimate what JavaScript runtime developers are capable of. Tweaking code to anticipate performance is a bad habit in higher-level languages like JavaScript. Worry about algorithms and good code. Commented Apr 20, 2013 at 22:43
  • 1
    A "particularly large" drain? No. Noticeable? Doubtful, but you can time it. Commented Apr 21, 2013 at 1:30

1 Answer 1

1

In older JS engines, scope lookups could cause some effects in performance.

However, even years back it was a very very minor difference - not really something you had to worry about.

Today's engines are most likely capable of optimizing lookups like this, and in general their performance is much much better. Unless you're writing something completely crazy or targeting a device with very poor performance, this is not something you need to worry about.

answered Apr 21, 2013 at 1:26
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.