High Performance JavaScript (YUIConf 2010)

17,829 views
16,358 views

Published on

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.

Published in: Technology
0 Comments
22 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
17,829
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
269
Comments
0
Likes
22
Embeds 0
No embeds

No notes for slide

High Performance JavaScript (YUIConf 2010)

  1. High Performance JavaScript Nicholas C. Zakas Yahoo!, Inc. YUIConf 2010 | November 9, 2010
  2. Greetings, program Principal Front End Engineer Contributor, Creator of YUI Test Author Lead Author Contributor Lead Author
  3. I know what you're thinking
  4. Is he really going to use a Tron theme throughout this presentation?
  5. Yes, because it's awesome
  6. JavaScript performance directly affects user experience
  7. "Know the enemy and know yourself; in a hundred battles you will never be in peril." -Sun Tzu, The Art of War
  8. The UI Thread The brains of the operation
  9. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
  10. Jobs for UI updates and JavaScript execution are added to a UI queue if the UI thread is busy Each job must wait in line for its turn to execute
  11. <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>
  12. Before Click UI Thread UI Queue time
  13. When Clicked UI Thread UI Queue time onclick UI Update UI Update
  14. When Clicked UI Thread UI Queue time onclick UI Update UI Update Draw down state
  15. When Clicked UI Thread UI Queue time onclick UI Update UI Update
  16. When Clicked UI Thread UI Queue time onclick UI UpdateUI Update Draw up state
  17. No UI updates while JavaScript is executing
  18. 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>
  19. A UI update must use the latest info available
  20. Long-running JavaScript = Unresponsive UI
  21. Responsive UI UI Thread time JavaScript UI UpdateUI Update
  22. Unresponsive UI UI Thread time JavaScript UI UpdateUI Update
  23. The longer JavaScript runs, the worse the user experience
  24. The browser vendors know this and put limits on JavaScript via the runaway script timer
  25. Internet Explorer
  26. Firefox
  27. Safari
  28. Chrome
  29. 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
  30. Does JIT compiling help?
  31. Interpreted JavaScript UI Thread time Interpret
  32. JITed JavaScript (1st Run) UI Thread time Compile Execute
  33. JITed JavaScript (After 1st Run) UI Thread time Execute
  34. 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
  35. Translation: No single JavaScript job should execute for more than 100ms to ensure a responsive UI
  36. Recommendation: Limit JavaScript execution to no more than 50ms measured on IE6 :)
  37. Loadtime Techniques Don't let JavaScript interfere with page load performance
  38. During page load, JavaScript takes more time on the UI thread
  39. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script src="foo.js"></script> <p>See ya!</p> </body> </html>
  40. Result UI Thread time JavaScript UI UpdateUI Update
  41. Result UI Thread time foo.js See ya!Hello world!
  42. Result UI Thread time Download See ya!Hello world! Parse Run The UI thread needs to wait for the script to download, parse, and run before continuing
  43. Result UI Thread Download time takes the longest and is variable Variable Constant UI Thread Download See ya!Hello world! Parse Run
  44. Translation: The page doesn't render while JavaScript is downloading, parsing, or executing during page load
  45. <!doctype html> <html> <head> <title>Example</title> </head> <body> <script src="foo.js"></script> <p>Hello world!</p> <script src="bar.js"></script> <p>See ya!</p> <script src="baz.js"></script> <p>Uh oh!</p> </body> </html>
  46. Result UI Thread time JavaScript UI UpdateUI Update The more scripts to download in between UI updates, the longer the page takes to render JavaScript JavaScript
  47. Technique #1: Put scripts at the bottom
  48. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <p>See ya!</p> <script src="foo.js"></script> </body> </html>
  49. Put Scripts at Bottom UI Thread time JavaScriptUI UpdateUI Update Even if there are multiple scripts, the page renders quickly JavaScript JavaScript
  50. Technique #2: Combine JavaScript files
  51. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <p>See ya!</p> <script src="foo.js"></script> <script src="bar.js"></script> <script src="baz.js"></script> </body> </html>
  52. UI Thread time JavaScriptUI Update Each script has overhead of downloading JavaScript JavaScript
  53. UI Thread time JavaScriptUI Update Combining all of the files limits the network overhead and gets scripts onto the page faster
  54. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <p>See ya!</p> <script src="foo-and-bar-and-baz.js"></script> </body> </html>
  55. Technique #3: Load scripts dynamically
  56. var script = document.createElement("script"), body; script.type = "text/javascript"; script.src = "foo.js"; body.insertBefore(script, body.firstChild); Basic Technique Dynamically loaded scripts are non-blocking
  57. Downloads no longer block the UI thread
  58. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script src="foo.js"></script> <p>See ya!</p> </body> </html>
  59. Using HTML <script> UI Thread time Download See ya!Hello world! Parse Run
  60. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script> var script = document.createElement("script"), body = document.body; script.type = "text/javascript"; script.src = "foo.js"; body.insertBefore(script, body.firstChild); </script> <p>See ya!</p><!-- more content --> </body> </html>
  61. Using Dynamic Scripts UI Thread time Download See ya!Hello world! Parse Run Only code execution happens on the UI thread, which means less blocking of UI updates UI Update
  62. function loadScript(url, callback){ var script = document.createElement("script"), body = document.body; script.type = "text/javascript"; if (script.readyState){ //IE <= 8 script.onreadystatechange = function(){ if (script.readyState == "loaded" || script.readyState == "complete"){ script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function(){ callback(); }; } script.src = url; body.insertBefore(script, body.firstChild); }
  63. loadScript("foo.js", function(){ alert("Loaded!"); }); Usage
  64. Timing Note: Script execution begins immediately after download and parse – timing of execution is not guaranteed
  65. Using Dynamic Scripts UI Thread time Download See ya!Hello world! Parse Run Depending on time to download and script size, execution may happen before next UI update UI Update
  66. Technique #4: Defer scripts
  67. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script defer src="foo.js"></script> <p>See ya!</p> <!-- even more markup --> </body> </html>
  68. 7.07.03.53.5 5.05.0 ??4.04.0 Support for <script defer>
  69. Deferred scripts begin to download immediately, but don't execute until all UI updates complete
  70. Using <script defer> UI Thread time Download See ya!Hello world! Parse Run Similar to dynamic script nodes, but with a guarantee that execution will happen last More UI More UI
  71. Timing Note: Although scripts always execute after UI updates complete, the order of multiple <script defer> scripts is not guaranteed across browsers
  72. Technique #5: Asynchronous scripts
  73. <!doctype html> <html> <head> <title>Example</title> </head> <body> <p>Hello world!</p> <script async src="foo.js"></script> <p>See ya!</p> <!-- even more markup --> </body> </html>
  74. 7.07.03.63.6 5.05.0 ???? Support for <script async>
  75. Asynchronous scripts behave a lot like dynamic scripts
  76. Using <script async> UI Thread time Download See ya!Hello world! Parse Run Download begins immediately and execution is slotted in at first available spot UI Update
  77. Note: Order of execution is explicitly not preserved for asynchronous scripts
  78. Runtime Techniques Ways to ensure JavaScript doesn't run away
  79. function processArray(items, process, callback){ for (var i=0,len=items.length; i < len; i++){ process(items[i]); } callback(); }
  80. Technique #1: Timers
  81. //create a new timer and delay by 500ms setTimeout(function(){ //code to execute here }, 500) setTimeout() schedules a function to be added to the UI queue after a delay
  82. 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); }
  83. When Clicked UI Thread UI Queue time onclick UI Update UI Update
  84. When Clicked UI Thread UI Queue time onclick UI Update UI Update
  85. When Clicked UI Thread UI Queue time onclick UI Update UI Update
  86. When Clicked UI Thread UI Queue time UI UpdateUI Update onclick
  87. After 25ms UI Thread UI Queue time UI UpdateUI Update onclick JavaScript
  88. After 25ms UI Thread UI Queue time UI UpdateUI Update onclick JavaScript
  89. After Another 25ms UI Thread UI Queue time UI UpdateUI Update onclick JavaScript JavaScript
  90. After Another 25ms UI Thread UI Queue time UI UpdateUI Update onclick JavaScript JavaScript
  91. Technique #2: Web Workers
  92. 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
  93. //in page var worker = new Worker("process.js"); worker.onmessage = function(event){ useData(event.data); }; worker.postMessage(values); //in process.js self.onmessage = function(event){ var items = event.data; for (var i=0,len=items.length; i < len; i++){ process(items[i]); } self.postMessage(items); };
  94. When Clicked UI Thread UI Queue time onclick UI Update UI Update
  95. When Clicked UI Thread UI Queue time onclick UI Update UI Update
  96. When Clicked UI Thread UI Queue time onclick UI Update UI Update
  97. When Clicked UI Thread UI Queue time onclick UI Update UI Update Worker Thread
  98. When Clicked UI Thread UI Queue time UI UpdateUI Update onclick Worker Thread JavaScript
  99. Worker Thread Complete UI Thread UI Queue time UI UpdateUI Update onclick onmessage
  100. Worker Thread Complete UI Thread UI Queue time UI UpdateUI Update onclick onmessage
  101. 4.04.03.53.5 4.04.0 10.610.6?? Support for Web Workers
  102. Repaint and Reflow Hidden performance costs of common operations
  103. Long UI updates = Unresponsive UI
  104. Unresponsive UI UI Thread time JavaScript UI UpdateUI Update
  105. JavaScript can cause long UI updates by triggering repaint and reflow
  106. A repaint occurs when a visual change doesn't require recalculation of layout Changes to visibility, colors (text/background), background images, etc.
  107. 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!
  108. A reflow occurs when a visual change requires a change in layout Initial page load ▪ browser resize ▪ DOM structure change ▪ layout style change layout information retrieved
  109. 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!
  110. Repaints and reflows are queued up as JavaScript executes and then executed in order
  111. 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!
  112. Limiting repaints/reflows improves overall performance
  113. Technique #1 Perform DOM manipulations off-document
  114. 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
  115. 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
  116. DocumentFragment var 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
  117. Technique #2 Group Style Changes
  118. element.style.color = "red"; element.style.height = "100px"; element.style.fontSize = "25px"; element.style.backgroundColor = "white"; Repaint! Reflow! Reflow! Repaint!
  119. .active { color: red; height: 100px; fontSize: 25px; background-color: white; } element.className = "active"; Reflow! Grouping Style Changes
  120. var item = document.getElementById("myItem"); item.style.cssText = "color:red;height:100px;" + "font-size:25px;background-color: white"); Reflow! Grouping Style Changes
  121. Technique #3 Avoid Accidental Reflow
  122. element.width = "100px"; var width = element.offsetWidth; Reflow! Accidental Reflow
  123. 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
  124. Does hardware acceleration help?
  125. Traditional Rendering UI Thread time Compositing Drawing
  126. Hardware Acceleration UI Thread timetime Prep GPU Compositing Rendering info Wait Drawing Signal complete
  127. Does JavaScript performance matter?
  128. After all, all browsers now have optimizing JavaScript engines Tracemonkey/ JaegarMonkey (3.5+) V8 (all) Squirrelfish (4+) Chakra (9+) Karakan (10.5+)
  129. So our scripts are getting really, really fast
  130. Old computers ran slow applications Small amounts of CPU power and memory
  131. New computers are generally faster but slow applications still exist More CPU + more memory = less disciplined application development
  132. It's still possible to write slow JavaScript on the new, faster JavaScript engines
  133. Recap
  134. awesome!!
  135. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
  136. Responsive UI UI Thread time JavaScript UI UpdateUI Update
  137. Unresponsive UI UI Thread time JavaScript UI UpdateUI Update
  138. Unresponsive UI UI Thread time JavaScript UI UpdateUI Update
  139. Avoid Slow Loading JavaScript • Put scripts at the bottom • Concatenate scripts into as few files as possible • Choose the right way to load your scripts – Dynamically created scripts – Deferred scripts – Asynchronous scripts
  140. Avoid Slow JavaScript • Don't allow JavaScript to execute for more than 50ms • Break up long JavaScript processes using: – Timers – Web Workers
  141. 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
  142. Etcetera • My blog: www.nczonline.net • Twitter: @slicknet • These Slides: http://slideshare.net/nzakas/ • Rate Me: http://spkr8.com/t/5000
  143. Questions?
  144. See ya!
  145. 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/

×