SenchaCon Day1: JavaScript Scope Change Optimizations

Doug Hendricks gives a talk on his take on JS scope.  Important to consider the burden we place on mobile devices that can’t recover as well from antipatterns.

Global variables (no var in front of them) exist through the life of the script and are public.  Also, those vars not declared inside a function. Node.js and HTML5 Workers use “global”.  Same as saying window.globalvar = 1.  Local variables, in contrast, are vars defined with the keyword “var” inside a function.

Activation objects are part of the scope chain right after global and can grow to have undesired effects. See slides for good explanation.

Scope chain augmentation used by closure, with and catch blocks.  Closures will always have 3 scope chain objects minimal.

Better to set a local variable to a global singleton like Ext to avoid having to traverse the scope chain to pull it from the global object.  Use this to refer to local stuff.  Replace scope-chain traversal with a single context text this for prototype search (e.g., ‘scope’: els).

Recommmendations:

  • declare frequently used vars as local vars to avoid scope chain traversal everytime
  • promote frequently used globals up the scope chain (creating local scope as necessary)
  • use closures and try/catch handlers sparingly as they too add to the activation objects on the scope chain
  • Forget about the ‘with’ clause (deprecated in ECMA JS 5)

The reason this is important is because the cycles to traverse the scope chain are expensive for mobile devices with limited power supply.  This is also fairly evident in IE 6/7 because the expense of ActiveX controls to manage this traversal.

Ways to avoid common mistakes/bottlenecks:

  • declare global references to functions that need to be used var doIt = function() {},
  • Avoid highly chained identifier. (e.g., var cust = some.cust.fav is much better instead of using the chain in each invocation)
  • Use function based iteration sparingly for light duty iteration in small sets
  • Don’t extend a class for something that isn’t used much (e.g., use this.constructor.prototype.initComponent.call(this) and set scope to ‘this’)

See thread 42942 on using pub/sub with Ext.util.Observable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s