Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Scope chain / Variable lookup performance

Tags:

javascript

I have seen a few articles explaining the resolution of variables using the scope chain in Javascript.

They all say variables are resolved at runtime walking up the scope chain and iteratively looking for a variable with that name. I've also seen graphs supporting that claim, illustrating the bad performance of variables high up the chain, with access times roughly linear in the number of scope levels of distance.

I'm not getting why the access times aren't constant. A variable name at a certain place creates a constant lexicographic binding. So I thought, naively, we should be able to represent the corresponding runtime variable reference instance with a reference to an execution context plus a reference to the variable relatively to that execution context.

Could you shed some light on why this isn't so.

like image 480
Jo So Avatar asked Sep 25 '26 14:09

Jo So


1 Answers

Today's JIT compilers like V8 might very well optimize some of this, but basically this is how it works:

For example, having a bunch of functions like this..

function foo() {
    function bar() {
    }
}

This would generate a closure for foo and a closure for bar. In order for a variable lookup to work, the interpreter would have to go up through the bounding closures to find the variable.

For example, in bar, a variable could be defined in

  • Inside function bar
  • Inside foo
  • In global scope

So here depending on how far up the variable is, the code would need to check all of them.

Now you of course could keep some kind of a table of variable names where the lookup would always be constant, but then you face another problem: Shadowed variables.

You could share the same name for variables inside nested functions. So this would present a problem in having a lookup table for variables based on the name. Of course again you could probably copy and build a lookup table for each function based on what variables are available, but this in turn ends up being a trade-off of speed vs memory consumption.

Without knowing the full details or implementations of today's JS engines, it's hard to say why it was designed the way it is. However, I think it's a reasonable enough system in that it performs okay without spending loads of memory. Also, if you wish to speed up variable lookups, it's always possible for you to assign variables into the local scope of your function, so you can optimize it manually if you so wish.

like image 120
Jani Hartikainen Avatar answered Sep 27 '26 04:09

Jani Hartikainen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!