high performance javascript - webdirections usa 2010

105
High Performance JavaScript Nicholas C. Zakas Yahoo!, Inc. The Web Industry Conference September 21–25, 2010 Midtown Atlanta

Upload: nicholas-zakas

Post on 10-May-2015

13.939 views

Category:

Technology


0 download

DESCRIPTION

Ever wonder why the page appears frozen or why you get a dialog saying, “this script is taking too long”? Inside of the browser, JavaScript and the page’s UI are very intertwined, which means they can affect each other and, in turn, affect overall page performance. Ensuring the fastest execution time of JavaScript code isn’t about geek cred, it’s about ensuring that the user experience is as fast and responsive as possible. In a world where an extra second can cost you a visitor, sluggishness due to poor JavaScript code is a big problem. In this talk, you’ll learn what’s going on inside the browser that can slow JavaScript down and how that can end up creating a “slow page”. You’ll also learn how to overcome the conspiracy against your code by eliminating performance bottlenecks.

TRANSCRIPT

Page 1: High Performance JavaScript - WebDirections USA 2010

High Performance JavaScriptNicholas C. ZakasYahoo!, Inc.

The Web Industry ConferenceSeptember 21–25, 2010Midtown Atlanta

Page 2: High Performance JavaScript - WebDirections USA 2010

Greetings, program

Principal Front End Engineer

Contributor,Creator of YUI Test

Author Lead Author Contributor Lead Author

Page 3: High Performance JavaScript - WebDirections USA 2010

I know what you're thinking

Page 4: High Performance JavaScript - WebDirections USA 2010

Is he really going to use a Tron theme throughout this

presentation?

Page 5: High Performance JavaScript - WebDirections USA 2010

Yes, because it's awesome

Page 6: High Performance JavaScript - WebDirections USA 2010

Well, mostly awsome

Page 7: High Performance JavaScript - WebDirections USA 2010

Does JavaScript performance matter?

Page 8: High Performance JavaScript - WebDirections USA 2010

After all, all browsers now haveoptimizing JavaScript engines

Tracemonkey/JaegarMonkey

(3.5+)

V8(all)

Squirrelfish (4+)

Chakra (9+)

Karakan(10.5+)

Page 9: High Performance JavaScript - WebDirections USA 2010

So our scripts are getting really, really fast

Page 10: High Performance JavaScript - WebDirections USA 2010

Old computers ran slow applications Small amounts of CPU power and memory

Page 11: High Performance JavaScript - WebDirections USA 2010

New computers are generally faster butslow applications still exist

More CPU + more memory = less disciplined application development

Page 12: High Performance JavaScript - WebDirections USA 2010

It's still possible to write slow JavaScript on the new, faster

JavaScript engines

Page 13: High Performance JavaScript - WebDirections USA 2010

JavaScript performancedirectly

affects user experience

Page 14: High Performance JavaScript - WebDirections USA 2010

"Know the enemy and know yourself; in a hundred battles you will never be in peril."

-Sun Tzu, The Art of War

Page 15: High Performance JavaScript - WebDirections USA 2010

The UI ThreadThe brains of the operation

Page 16: High Performance JavaScript - WebDirections USA 2010

The browser UI thread is responsible forboth UI updates and JavaScript execution

Only one can happen at a time

Page 17: High Performance JavaScript - WebDirections USA 2010

Jobs for UI updates and JavaScript execution areadded to a UI queue if the UI thread is busy

Each job must wait in line for its turn to execute

Page 18: High Performance JavaScript - WebDirections USA 2010

<button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button>

<script type="text/javascript">window.onload = function(){ document.getElementById("btn").onclick = function(){ //do something };};</script>

Page 19: High Performance JavaScript - WebDirections USA 2010

Before Click

UI Thread

UI Queue

time

Page 20: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Page 21: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Draw down state

Page 22: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Page 23: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick UI UpdateUI Update

Draw up state

Page 24: High Performance JavaScript - WebDirections USA 2010

No UI updates while JavaScript is executing

Page 25: High Performance JavaScript - WebDirections USA 2010

JavaScript May Cause UI Update

<button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button>

<script type="text/javascript">window.onload = function(){ document.getElementById("btn").onclick = function(){ var div = document.createElement(“div”); div.className = “tip”; div.innerHTML = “You clicked me!”; document.body.appendChild(div); };};</script>

Page 26: High Performance JavaScript - WebDirections USA 2010

A UI update must use the latest info available

Page 27: High Performance JavaScript - WebDirections USA 2010

Long-running JavaScript=

Unresponsive UI

Page 28: High Performance JavaScript - WebDirections USA 2010

Responsive UI

UI Thread

time

JavaScript UI UpdateUI Update

Page 29: High Performance JavaScript - WebDirections USA 2010

Unresponsive UI

UI Thread

time

JavaScript UI UpdateUI Update

Page 30: High Performance JavaScript - WebDirections USA 2010

The longer JavaScript runs,the worse the user experience

Page 31: High Performance JavaScript - WebDirections USA 2010

The browser vendors know this and put limits on JavaScript via therunaway script timer

Page 32: High Performance JavaScript - WebDirections USA 2010

Internet Explorer

Page 33: High Performance JavaScript - WebDirections USA 2010

Firefox

Page 34: High Performance JavaScript - WebDirections USA 2010

Safari

Page 35: High Performance JavaScript - WebDirections USA 2010

Chrome

Page 36: High Performance JavaScript - WebDirections USA 2010

Runaway Script Timer Limits• Internet Explorer: 5 million statements• Firefox: 10 seconds• Safari: 5 seconds• Chrome: Unknown, hooks into normal crash

control mechanism• Opera: none

Page 37: High Performance JavaScript - WebDirections USA 2010

Does JIT compiling help?

Page 38: High Performance JavaScript - WebDirections USA 2010

Interpreted JavaScript

UI Thread

time

Interpret

Page 39: High Performance JavaScript - WebDirections USA 2010

JITed JavaScript (1st Run)

UI Thread

time

Compile Execute

Page 40: High Performance JavaScript - WebDirections USA 2010

JITed JavaScript (After 1st Run)

UI Thread

time

Execute

Page 41: High Performance JavaScript - WebDirections USA 2010

How Long Is Too Long?

“0.1 second [100ms] is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.”

- Jakob Nielsen

Page 42: High Performance JavaScript - WebDirections USA 2010

Translation:No single JavaScript job should execute for more than 100ms to

ensure a responsive UI

Page 43: High Performance JavaScript - WebDirections USA 2010

Recommendation:Limit JavaScript execution to no more

than 50ms

measured on IE6 :)

Page 44: High Performance JavaScript - WebDirections USA 2010

TechniquesWays to ensure JavaScript doesn't run away

Page 45: High Performance JavaScript - WebDirections USA 2010

function processArray(items, process, callback){ for (var i=0,len=items.length; i < len; i++){ process(items[i]); } callback();}

Page 46: High Performance JavaScript - WebDirections USA 2010

Technique #1: Timers

Page 47: High Performance JavaScript - WebDirections USA 2010

//create a new timer and delay by 500mssetTimeout(function(){

//code to execute here

}, 500)

setTimeout() schedules a function to be added to the UI queue after a delay

Page 48: High Performance JavaScript - WebDirections USA 2010

function timedProcessArray(items, process, callback){ //create a clone of the original

var todo = items.concat(); setTimeout(function(){ var start = +new Date(); do { process(todo.shift()); } while (todo.length > 0 && (+new Date() - start < 50)); if (todo.length > 0){ setTimeout(arguments.callee, 25); } else { callback(items); } }, 25);}

Page 49: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Page 50: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Page 51: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Page 52: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

UI UpdateUI Update onclick

Page 53: High Performance JavaScript - WebDirections USA 2010

After 25ms

UI Thread

UI Queue

time

UI UpdateUI Update onclick

JavaScript

Page 54: High Performance JavaScript - WebDirections USA 2010

After 25ms

UI Thread

UI Queue

time

UI UpdateUI Update onclick JavaScript

Page 55: High Performance JavaScript - WebDirections USA 2010

After Another 25ms

UI Thread

UI Queue

time

UI UpdateUI Update onclick JavaScript

JavaScript

Page 56: High Performance JavaScript - WebDirections USA 2010

After Another 25ms

UI Thread

UI Queue

time

UI UpdateUI Update onclick JavaScript JavaScript

Page 57: High Performance JavaScript - WebDirections USA 2010

Technique #2: Web Workers

Page 58: High Performance JavaScript - WebDirections USA 2010
Page 59: High Performance JavaScript - WebDirections USA 2010

Web Workers

● Asynchronous JavaScript execution● Execution happens outside of UI thread

● Not on the UI thread = no UI delays● Data-driven API

● Data is serialized when sending data into or out of Worker

● No access to DOM, BOM● Completely separate execution environment

Page 60: High Performance JavaScript - WebDirections USA 2010

//in pagevar worker = new Worker("process.js");worker.onmessage = function(event){ useData(event.data);};worker.postMessage(values);

//in process.jsself.onmessage = function(event){ var items = event.data; for (var i=0,len=items.length; i < len; i++){ process(items[i]); } self.postMessage(items);};

Page 61: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Page 62: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Page 63: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Page 64: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

onclick

UI Update

UI Update

Worker Thread

Page 65: High Performance JavaScript - WebDirections USA 2010

When Clicked

UI Thread

UI Queue

time

UI UpdateUI Update onclick

Worker Thread

JavaScript

Page 66: High Performance JavaScript - WebDirections USA 2010

Worker Thread Complete

UI Thread

UI Queue

time

UI UpdateUI Update onclick

onmessage

Page 67: High Performance JavaScript - WebDirections USA 2010

Worker Thread Complete

UI Thread

UI Queue

time

UI UpdateUI Update onclick onmessage

Page 68: High Performance JavaScript - WebDirections USA 2010

Web Workers Support

4.04.03.53.5 4.04.0 10.610.6

Page 69: High Performance JavaScript - WebDirections USA 2010

Repaint and ReflowHidden performance costs of common operations

Page 70: High Performance JavaScript - WebDirections USA 2010

Long UI updates=

Unresponsive UI

Page 71: High Performance JavaScript - WebDirections USA 2010

Unresponsive UI

UI Thread

time

JavaScript UI UpdateUI Update

Page 72: High Performance JavaScript - WebDirections USA 2010

JavaScript can cause long UI updates by triggering

repaint and reflow

Page 73: High Performance JavaScript - WebDirections USA 2010

A repaint occurs when a visual change doesn't require recalculation of layout

Changes to visibility, colors (text/background), background images, etc.

Page 74: High Performance JavaScript - WebDirections USA 2010

Repaint

<button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button>

<script type="text/javascript">window.onload = function(){ document.getElementById("btn").onclick = function(){ this.style.color = "#ff0"; };};</script> Repaint!

Page 75: High Performance JavaScript - WebDirections USA 2010

A reflow occurs when a visual change requires a change in layout

Initial page load ▪ browser resize ▪ DOM structure change ▪ layout style changelayout information retrieved

Page 76: High Performance JavaScript - WebDirections USA 2010

Reflow

<button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button>

<script type="text/javascript">window.onload = function(){ document.getElementById("btn").onclick = function(){ var div = document.createElement(“div”); div.className = “tip”; div.innerHTML = “You clicked me!”; document.body.appendChild(div); };};</script> Reflow!

Page 77: High Performance JavaScript - WebDirections USA 2010

Repaints and reflows are queued up as JavaScript executes

and then executed in order

Page 78: High Performance JavaScript - WebDirections USA 2010

Reflow

var list = document.getElementsByClassName("items")[0], i, item;

for (i=0; i < 10; i++){ item = document.createElement("li"); item.innerHTML = "Item #" + i; list.appendChild(item);}

Reflow x 10!

Page 79: High Performance JavaScript - WebDirections USA 2010

Limiting repaints/reflows improves overall performance

Page 80: High Performance JavaScript - WebDirections USA 2010

Technique #1Perform DOM manipulations

off-document

Page 81: High Performance JavaScript - WebDirections USA 2010

Off-Document Operations

• Fast because there's no repaint/reflow• Techniques:

– Remove element from the document, make changes, insert back into document

– Set element's display to “none”, make changes, set display back to default

– Build up DOM changes on a DocumentFragment then apply all at once

Page 82: High Performance JavaScript - WebDirections USA 2010

DocumentFragment• A document-like object• Not visually represented• Considered to be owned by the document from

which it was created• When passed to appendChild(), appends all

of its children rather than itself

Page 83: High Performance JavaScript - WebDirections USA 2010

DocumentFragmentvar list = document.getElementsByClassName("items")[0], fragment = document.createDocumentFragment(), i, item;

for (i=0; i < 10; i++){ item = document.createElement("li"); item.innerHTML = "Item #" + i; fragment.appendChild(item);}list.appendChild(fragment);

1 Reflow

Page 84: High Performance JavaScript - WebDirections USA 2010

Technique #2Group Style Changes

Page 85: High Performance JavaScript - WebDirections USA 2010

element.style.color = "red";element.style.height = "100px";element.style.fontSize = "25px";element.style.backgroundColor = "white";

Repaint! Reflow!

Reflow!

Repaint!

Page 86: High Performance JavaScript - WebDirections USA 2010

.active { color: red; height: 100px; fontSize: 25px; background-color: white;}

element.className = "active";

Reflow!

Grouping Style Changes

Page 87: High Performance JavaScript - WebDirections USA 2010

var item = document.getElementById("myItem");item.style.cssText = "color:red;height:100px;" + "font-size:25px;background-color: white");

Reflow!

Grouping Style Changes

Page 88: High Performance JavaScript - WebDirections USA 2010

Technique #3Avoid Accidental Reflow

Page 89: High Performance JavaScript - WebDirections USA 2010

element.width = "100px";

var width = element.offsetWidth;

Reflow!

Accidental Reflow

Page 90: High Performance JavaScript - WebDirections USA 2010

What to do?• Minimize access to layout information

– offsetTop, offsetLeft, offsetWidth, offsetHeight– scrollTop, scrollLeft, scrollWidth, scrollHeight– clientTop, clientLeft, clientWidth, clientHeight– Most computed styles

• If a value is used more than once, store in local variable

Page 91: High Performance JavaScript - WebDirections USA 2010

Does hardware acceleration help?

Page 92: High Performance JavaScript - WebDirections USA 2010

Traditional Rendering

UI Thread

time

Compositing Drawing

Page 93: High Performance JavaScript - WebDirections USA 2010

Hardware Acceleration

UI Thread

timetime

Prep

GPU

Compositing

Rendering info

Wait

Drawing

Signal complete

Page 94: High Performance JavaScript - WebDirections USA 2010

Recap

Page 95: High Performance JavaScript - WebDirections USA 2010

awesome!!

Page 96: High Performance JavaScript - WebDirections USA 2010

The browser UI thread is responsible forboth UI updates and JavaScript execution

Only one can happen at a time

Page 97: High Performance JavaScript - WebDirections USA 2010

Responsive UI

UI Thread

time

JavaScript UI UpdateUI Update

Page 98: High Performance JavaScript - WebDirections USA 2010

Unresponsive UI

UI Thread

time

JavaScript UI UpdateUI Update

Page 99: High Performance JavaScript - WebDirections USA 2010

Unresponsive UI

UI Thread

time

JavaScript UI UpdateUI Update

Page 100: High Performance JavaScript - WebDirections USA 2010

Avoid Slow JavaScript• Don't allow JavaScript to execute for more

than 50ms• Break up long JavaScript processes using:

– Timers– Web Workers

Page 101: High Performance JavaScript - WebDirections USA 2010

Avoid Long UI Updates• Be careful of repaint and reflow• Perform complex DOM operations off-

document– Remove elements and re-add them– Use DocumentFragment objects

• Group style changes together• Avoid accidental reflow

Page 102: High Performance JavaScript - WebDirections USA 2010

Etcetera• My blog:

www.nczonline.net• My email:

[email protected]• Twitter:

@slicknet• These Slides:

http://slideshare.net/nzakas/presentations/• Rate Me:

http://spkr8.com/t/4511

Page 103: High Performance JavaScript - WebDirections USA 2010

Questions?

Page 104: High Performance JavaScript - WebDirections USA 2010

See ya!

Page 105: High Performance JavaScript - WebDirections USA 2010

Creative Commons Images Used• http://www.flickr.com/photos/hippie/2406411610/

• http://www.flickr.com/photos/55733754@N00/3325000738/

• http://www.flickr.com/photos/eurleif/255241547/

• http://www.flickr.com/photos/off_the_wall/3444915939/

• http://www.flickr.com/photos/wwarby/3296379139/

• http://www.flickr.com/photos/derekgavey/4358797365/

• http://www.flickr.com/photos/mulad/286641998/

• http://www.flickr.com/photos/torley/2361164281/

• http://www.flickr.com/photos/ottoman42/455242/