JavaScript Variable Performance

13
JavaS cript Variable Performance Nicholas C. Zakas Principal Front End Engineer, Yahoo!

description

My talk at the January 21, 2009 Mountain View JavaScript Meetup about the performance of JavaScript variables relative to their position in the scope chain.

Transcript of JavaScript Variable Performance

Page 1: JavaScript Variable Performance

JavaS cript Variable PerformanceNicholas C. Zakas

Principal Front End Engineer, Yahoo!

Page 2: JavaScript Variable Performance
Page 3: JavaScript Variable Performance
Page 4: JavaScript Variable Performance

S cope Chains

Page 5: JavaScript Variable Performance

When a Function Executes• An execution context is created• The context's scope chain is initialized

with the members of the function's [[S cope]] collection

• An activation object is created containing all local variables

• The activation object is pushed to the front of the context's scope chain

Page 6: JavaScript Variable Performance

Execution Context

Identifier Resolution• S tart at scope chain position 0• If not found go to position 1• And so on

Page 7: JavaScript Variable Performance

Identifier Resolution• Local variables = fast!• The further into the chain, the slower the

resolution

Page 8: JavaScript Variable Performance

Identifier Resolution (Reads)

1 2 3 4 5 6

Identifier Depth

Tim

e

Firefox 3Firefox 3.1 Beta 2Google Chrome 1Internet Explorer 7Internet Explorer 8 Beta 2Opera 9.62Safari 3.1 (525.13)Safari 3.2 (525.27.1)WebKit Nightly (528+)

Page 9: JavaScript Variable Performance

Identifier Resolution (Writes )

1 2 3 4 5 6

Identifier Depth

Tim

e

Firefox 3Firefox 3.1 Beta 2Google Chrome 1Internet Explorer 7Internet Explorer 8 Beta 2Opera 9.62Safari 3.1 (525.13)Safari 3.2 (525.27.1)WebKit Nightly (528+)

Page 10: JavaScript Variable Performance

Recommendations• S tore local references to out-of-scope

variables– E specially global variables

• Avoid the with statement– Adds another object to the scope chain, so

local function variables are now one step away

Page 11: JavaScript Variable Performance
Page 12: JavaScript Variable Performance
Page 13: JavaScript Variable Performance

Etcetera• My blog: www.nczonline.net• My email: nzakas@ yahoo-inc.com• Twitter: @ slicknet