Top Banner
Speed Up Your JavaScript Nicholas C. Zakas Principal Front End Engineer, Yahoo! Web E x ponents – June 4, 2009
90

Speed Up Your JavaScript

Sep 08, 2014

Download

Technology

Nicholas Zakas

Describes common JavaScript performance issues and how to work around them.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Speed Up Your JavaScript

Speed Up Your JavaScriptNicholas C. Zakas

Principal Front End Engineer, Yahoo!Web Exponents – June 4, 2009

Page 2: Speed Up Your JavaScript

Who's this guy?• Principal Front End Engineer, Yahoo! Homepage• YUI Contributor• Author

Page 3: Speed Up Your JavaScript
Page 4: Speed Up Your JavaScript

Why slow?

Page 5: Speed Up Your JavaScript

Bad compilation?

Page 6: Speed Up Your JavaScript

No

Page 7: Speed Up Your JavaScript

No compilation!*

* Humor me for now. It'll make this easier.

Page 8: Speed Up Your JavaScript

Browsers won'thelp yourcode!!!!

Page 9: Speed Up Your JavaScript

Who will help your code?

Page 10: Speed Up Your JavaScript
Page 11: Speed Up Your JavaScript

JavaScript Performance Issues• Scope management• Data access• Loops• DOM

Page 12: Speed Up Your JavaScript
Page 13: Speed Up Your JavaScript

Scope Chains

Page 14: Speed Up Your JavaScript

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

members of the function's [[Scope]] 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 15: Speed Up Your JavaScript

Execution Context

Identifier Resolution• Start at scope chain position 0• If not found go to position 1• Rinse, repeat

Page 16: Speed Up Your JavaScript

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

resolution

Page 17: Speed Up Your JavaScript

Identifier Resolution (Reads)

0

20

40

60

80

100

120

140

160

180

200

1 2 3 4 5 6

Identifier Depth

Tim

e (m

s) p

er 2

00,0

00 re

ads Firefox 3

Firefox 3.1 Beta 3Chrome 1Chrome 2 BetaInternet Explorer 7Internet Explorer 8Opera 9.64Opera 10 AlphaSafari 3.2Safari 4 Beta

Page 18: Speed Up Your JavaScript

Identifier Resolution (Writes)

0

20

40

60

80

100

120

140

160

180

200

1 2 3 4 5 6

Identifier Depth

Tim

e (m

s) p

er 2

00,0

00 w

rites Firefox 3

Firefox 3.1 Beta 3Chrome 1Chrome 2 BetaInternet Explorer 7Internet Explorer 8Opera 9.64Opera 10 AlphaSafari 3.2Safari 4 Beta

Page 19: Speed Up Your JavaScript

Scope Chain Augmentation• The with statement• The catch clause of try-catch• Both add an object to the front of the scope chain

Page 20: Speed Up Your JavaScript

Inside of Global Function

Page 21: Speed Up Your JavaScript

Inside of with/catch Statement

• Local variables now in second slot• with variables now in first slot

Page 22: Speed Up Your JavaScript

“with statement considered harmful”-Douglas Crockford

Page 23: Speed Up Your JavaScript

Closures• The [[Scope]] property of closures begins with two

objects• Calling the closure means three objects in the

scope chain (minimum)

Page 24: Speed Up Your JavaScript
Page 25: Speed Up Your JavaScript

Closures

Page 26: Speed Up Your JavaScript

Inside of Closure

Page 27: Speed Up Your JavaScript

Recommendations• Store out-of-scope variables in local variables

– Especially global variables• Avoid the with statement

– Adds another object to the scope chain, so local function variables are now one step away

– Use local variables instead• Be careful with try-catch

– The catch clause also augments the scope chain• Use closures sparingly• Don't forget var when declaring variables

Page 28: Speed Up Your JavaScript
Page 29: Speed Up Your JavaScript

JavaScript Performance Issues• Scope management• Data access• Loops• DOM

Page 30: Speed Up Your JavaScript

Places to Access Data• Literal value• Variable• Object property• Array item

Page 31: Speed Up Your JavaScript

Data Access Performance• Accessing data from a literal or a local variable is

fastest– The difference between literal and local variable is

negligible in most cases• Accessing data from an object property or array

item is more expensive– Which is more expensive depends on the browser

Page 32: Speed Up Your JavaScript

Data Access

0

10

20

30

40

50

60

70

80

90

100

Firefox 3 Firefox 3.1Beta 3

Chrome 1 Chrome 2Beta

InternetExplorer 7

InternetExplorer 8

Opera 9.64 Opera 10Alpha

Safari 3.2 Safari 4Beta

Tim

e (m

s) p

er 2

00,0

00 re

ads

LiteralLocal VariableArray ItemObject Property

Page 33: Speed Up Your JavaScript

Property Depth• object.name < object.name.name• The deeper the property, the longer it takes to

retrieve

Page 34: Speed Up Your JavaScript

Property Depth

0

50

100

150

200

250

1 2 3 4

Property Depth

Tim

e (m

s) p

er 2

00,0

00 re

ads Firefox 3

Firefox 3.1 Beta 3Chrome 1Chrome 2 BetaInternet Explorer 7Internet Explorer 8Opera 9.64Opera 10 AlphaSafari 3.2Safari 4 Beta

Page 35: Speed Up Your JavaScript

Property Notation• Difference between object.name and object[“name”]?– Generally no– Exception: Dot notation is faster in Safari

Page 36: Speed Up Your JavaScript

Recommendations• Store these in a local variable:

– Any object property accessed more than once– Any array item accessed more than once

• Minimize deep object property/array item lookup

Page 37: Speed Up Your JavaScript
Page 38: Speed Up Your JavaScript

-5% -33%-10%

Page 39: Speed Up Your JavaScript

JavaScript Performance Issues• Scope management• Data Access• Loops• DOM

Page 40: Speed Up Your JavaScript

Loops• ECMA-262, 3rd Edition:

– for– for-in– do-while– while

• ECMA-357, 2nd Edition:– for each

Page 41: Speed Up Your JavaScript
Page 42: Speed Up Your JavaScript

Which loop?

Page 43: Speed Up Your JavaScript

It doesn't matter!

Page 44: Speed Up Your JavaScript

What Does Matter?• Amount of work done per iteration

– Includes terminal condition evaluation and incrementing/decrementing

• Number of iterations• These don't vary by loop type

Page 45: Speed Up Your JavaScript

Fixing Loops• Decrease amount of work per iteration• Decrease number of iterations

Page 46: Speed Up Your JavaScript
Page 47: Speed Up Your JavaScript
Page 48: Speed Up Your JavaScript
Page 49: Speed Up Your JavaScript

Easy Fixes• Eliminate object property/array item lookups

Page 50: Speed Up Your JavaScript
Page 51: Speed Up Your JavaScript

Easy Fixes• Eliminate object property/array item lookups• Combine control condition and control variable

change– Work avoidance!

Page 52: Speed Up Your JavaScript

Two evaluations:j < lenj < len == true

Page 53: Speed Up Your JavaScript

-50%

One evaluationj-- == true

Page 54: Speed Up Your JavaScript

Easy Fixes• Eliminate object property/array item lookups• Combine control condition and control variable

change– Work avoidance!

Page 55: Speed Up Your JavaScript

Things to Avoid for Speed• ECMA-262, 3rd Edition:

– for-in• ECMA-357, 2nd Edition:

– for each• ECMA-262, 5th Edition:

– array.forEach()• Function-based iteration:

– jQuery.each()– Y.each()– $each– Enumerable.each()

Page 56: Speed Up Your JavaScript

• Introduces additional function• Function requires execution (execution context

created, destroyed)• Function also creates additional object in scope

chain

8x

Page 57: Speed Up Your JavaScript

JavaScript Performance Issues• Scope management• Data Access• Loops• DOM

Page 58: Speed Up Your JavaScript

DOM

Page 59: Speed Up Your JavaScript

HTMLCollection

Page 60: Speed Up Your JavaScript

HTMLCollection Objects• document.images, document.forms,

etc.• getElementsByTagName()• getElementsByClassName()

Page 61: Speed Up Your JavaScript

Note: Collections in the HTML DOM are assumed to be livemeaning that they are automatically updated when the underlying

document is changed.

Page 62: Speed Up Your JavaScript

Infinite Loop!

Page 63: Speed Up Your JavaScript

HTMLCollection Objects• Look like arrays, but aren't

– Bracket notation– length property

• Represent the results of a specific query• The query is re-run each time the object is

accessed– Include accessing length and specific items– Much slower than accessing the same on arrays– Exceptions: Opera, Safari

Page 64: Speed Up Your JavaScript

15x 68x53x

Page 65: Speed Up Your JavaScript

= ==

Page 66: Speed Up Your JavaScript

HTMLCollection Objects• Minimize property access

– Store length, items in local variables if used frequently• If you need to access items in order frequently,

copy into a regular array

Page 67: Speed Up Your JavaScript

function array(items){ try { return Array.prototype.slice.call(items); } catch (ex){ var i = 0, len = items.length, result = Array(len);

while (i < len){ result[i] = items[i]; i++; } } return result;}

Page 68: Speed Up Your JavaScript

Reflow

Page 69: Speed Up Your JavaScript

Reflow is the process by which the geometry of the layout engine's formatting objects are computed.

- Chris Waterson, Mozilla

Page 70: Speed Up Your JavaScript

When Reflow?• Initial page load• Browser window resize• DOM nodes added or removed• Layout styles applied• Layout information retrieved

Page 71: Speed Up Your JavaScript

Reflow!

Page 72: Speed Up Your JavaScript

DocumentFragment• A document-like object• Not visually represented• Considered a child of the document from which it

was created• When passed to addChild(), appends all of

its children rather than itself

Page 73: Speed Up Your JavaScript

Reflow!

No reflow!

Page 74: Speed Up Your JavaScript

When Reflow?• Initial page load• Browser window resize• DOM nodes added or removed• Layout styles applied• Layout information retrieved

Page 75: Speed Up Your JavaScript

Reflow!

Reflow! Reflow!

Page 76: Speed Up Your JavaScript

What to do?• Minimize changes on style property• Define CSS class with all changes and just

change className property

Page 77: Speed Up Your JavaScript

Reflow!

Page 78: Speed Up Your JavaScript

When Reflow?• Initial page load• Browser window resize• DOM nodes added or removed• Layout styles applied• Layout information retrieved

– Only if reflow is cached

Page 79: Speed Up Your JavaScript

Reflow?Reflow?

Reflow?

Page 80: Speed Up Your JavaScript

What to do?• Minimize access to layout information• If a value is used more than once, store in local

variable

Page 81: Speed Up Your JavaScript

Speed Up Your DOM• Be careful using HTMLCollection objects• Perform DOM manipulations off the document• Change CSS classes, not CSS styles• Be careful when accessing layout information

Page 82: Speed Up Your JavaScript
Page 83: Speed Up Your JavaScript

Will it be like this forever?

Page 84: Speed Up Your JavaScript

No

Page 85: Speed Up Your JavaScript

Browsers With Optimizing Engines• Chrome (V8)• Safari 4+ (Nitro)• Firefox 3.5+ (TraceMonkey)• Opera 10? 11? (Carakan)

All use native code generation and JIT compiling to achieve faster JavaScript execution.

Page 86: Speed Up Your JavaScript

Hang in there!

Page 87: Speed Up Your JavaScript

Summary• Mind your scope• Local variables are your friends• Function execution comes at a cost• Keep loops small• Avoid doing work whenever possible• Minimize DOM interaction• Use a good browser and encourage others to do

the same

Page 88: Speed Up Your JavaScript

Questions?

Page 89: Speed Up Your JavaScript

Etcetera• My blog: www.nczonline.net• My email: [email protected]• Twitter: @slicknet

Page 90: Speed Up Your JavaScript

Creative Commons Images Used• http://www.flickr.com/photos/blackbutterfly/3051019058/• http://www.flickr.com/photos/23816315@N07/2528296337/• http://www.flickr.com/photos/37287477@N00/515178157/• http://www.flickr.com/photos/ottoman42/455242/• http://www.flickr.com/photos/crumbs/2702429363/• http://flickr.com/photos/oberazzi/318947873/