High Performance JavaScript - WebDirections USA 2010

24,286 views
22,445 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
6 Comments
67 Likes
Statistics
Notes
  • JavaScript: Crash Course - The Ultimate Beginner's Course to Learning JavaScript Programming in Under 12 Hours --- http://amzn.to/1SaRAjU
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • JavaScript and JQuery: Interactive Front-End Web Development --- http://amzn.to/22vHpLC
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • A Smarter Way to Learn JavaScript: The new approach that uses technology to cut your effort in half --- http://amzn.to/1UdwapY
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Another excellent presentation. Also a big fan of your book, High Performance JavaScript.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • High Performance JavaScript
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
24,286
On SlideShare
0
From Embeds
0
Number of Embeds
2,357
Actions
Shares
0
Downloads
597
Comments
6
Likes
67
Embeds 0
No embeds

No notes for slide

High Performance JavaScript - WebDirections USA 2010

  1. High Performance JavaScript Nicholas C. Zakas Yahoo!, Inc. The Web Industry Conference September 21–25, 2010 Midtown Atlanta
  2. Greetings, program Principal Front End Contributor, Engineer 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. Well, mostly awsome
  7. Does JavaScript performance matter?
  8. After all, all browsers now have optimizing JavaScript engines Tracemonkey/ V8 Squirrelfish Chakra Karakan JaegarMonkey (all) (4+) (9+) (10.5+) (3.5+)
  9. So our scripts are getting really, really fast
  10. Old computers ran slow applications Small amounts of CPU power and memory
  11. New computers are generally faster but slow applications still exist More CPU + more memory = less disciplined application development
  12. It's still possible to write slow JavaScript on the new, faster JavaScript engines
  13. JavaScript performance directly affects user experience
  14. "Know the enemy and know yourself; in a hundred battles you will never be in peril." -Sun Tzu, The Art of War
  15. The UI Thread The brains of the operation
  16. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
  17. 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
  18. <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>
  19. Before Click UI Thread time UI Queue
  20. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  21. When Clicked UI Thread UI Update time UI Queue onclick Draw down state UI Update
  22. When Clicked UI Thread UI Update onclick time UI Queue UI Update
  23. When Clicked UI Thread UI Update onclick UI Update time UI Queue Draw up state
  24. No UI updates while JavaScript is executing
  25. 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>
  26. A UI update must use the latest info available
  27. Long-running JavaScript = Unresponsive UI
  28. Responsive UI UI Thread UI Update JavaScript UI Update time
  29. Unresponsive UI UI Thread UI Update JavaScript UI Update time
  30. The longer JavaScript runs, the worse the user experience
  31. The browser vendors know this and put limits on JavaScript via the runaway script timer
  32. Internet Explorer
  33. Firefox
  34. Safari
  35. Chrome
  36. 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
  37. Does JIT compiling help?
  38. Interpreted JavaScript UI Thread Interpret time
  39. JITed JavaScript (1st Run) UI Thread Compile Execute time
  40. JITed JavaScript (After 1st Run) UI Thread Execute time
  41. 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
  42. Translation: No single JavaScript job should execute for more than 100ms to ensure a responsive UI
  43. Recommendation: Limit JavaScript execution to no more than 50ms measured on IE6 :)
  44. Techniques Ways to ensure JavaScript doesn't run away
  45. function processArray(items, process, callback){ for (var i=0,len=items.length; i < len; i++){ process(items[i]); } callback(); }
  46. Technique #1: Timers
  47. //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
  48. 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); }
  49. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  50. When Clicked UI Thread UI Update time UI Queue onclick UI Update
  51. When Clicked UI Thread UI Update onclick time UI Queue UI Update
  52. When Clicked UI Thread UI Update onclick UI Update time UI Queue
  53. After 25ms UI Thread UI Update onclick UI Update time UI Queue JavaScript
  54. After 25ms UI Thread UI Update onclick UI Update JavaScript time UI Queue
  55. After Another 25ms UI Thread UI Update onclick UI Update JavaScript time UI Queue JavaScript
  56. After Another 25ms UI Thread UI Update onclick UI Update JavaScript JavaScript time UI Queue
  57. Technique #2: Web Workers
  58. 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
  59. //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); };
  60. When Clicked UI Thread time UI Queue UI Update onclick UI Update
  61. When Clicked UI Thread UI Update time UI Queue onclick UI Update
  62. When Clicked UI Thread UI Update onclick time UI Queue UI Update
  63. When Clicked UI Thread UI Update onclick time Worker Thread UI Queue UI Update
  64. When Clicked UI Thread UI Update onclick UI Update time Worker Thread UI Queue JavaScript
  65. Worker Thread Complete UI Thread UI Update onclick UI Update time UI Queue onmessage
  66. Worker Thread Complete UI Thread UI Update onclick UI Update onmessage time UI Queue
  67. Web Workers Support 3.5 4.0 4.0 10.6
  68. Repaint and Reflow Hidden performance costs of common operations
  69. Long UI updates = Unresponsive UI
  70. Unresponsive UI UI Thread UI Update JavaScript UI Update time
  71. JavaScript can cause long UI updates by triggering repaint and reflow
  72. A repaint occurs when a visual change doesn't require recalculation of layout Changes to visibility, colors (text/background), background images, etc.
  73. 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!
  74. 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
  75. 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!
  76. Repaints and reflows are queued up as JavaScript executes and then executed in order
  77. 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!
  78. Limiting repaints/reflows improves overall performance
  79. Technique #1 Perform DOM manipulations off-document
  80. 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
  81. 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
  82. 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
  83. Technique #2 Group Style Changes
  84. Repaint! Reflow! element.style.color = "red"; element.style.height = "100px"; Reflow! element.style.fontSize = "25px"; element.style.backgroundColor = "white"; Repaint!
  85. Grouping Style Changes .active { color: red; height: 100px; fontSize: 25px; background-color: white; } element.className = "active"; Reflow!
  86. Grouping Style Changes var item = document.getElementById("myItem"); item.style.cssText = "color:red;height:100px;" + "font-size:25px;background-color: white"); Reflow!
  87. Technique #3 Avoid Accidental Reflow
  88. Accidental Reflow element.width = "100px"; var width = element.offsetWidth; Reflow!
  89. 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
  90. Does hardware acceleration help?
  91. Traditional Rendering UI Thread Compositing Drawing time
  92. Hardware Acceleration UI Thread Prep Wait time Rendering info Signal complete Compositing Drawing GPU
  93. Recap
  94. awesome!!
  95. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
  96. Responsive UI UI Thread UI Update JavaScript UI Update time
  97. Unresponsive UI UI Thread UI Update JavaScript UI Update time
  98. Unresponsive UI UI Thread UI Update JavaScript UI Update time
  99. Avoid Slow JavaScript • Don't allow JavaScript to execute for more than 50ms • Break up long JavaScript processes using: – Timers – Web Workers
  100. 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
  101. Etcetera • My blog: www.nczonline.net • My email: nzakas@yahoo-inc.com • Twitter: @slicknet • These Slides: http://slideshare.net/nzakas/presentations/ • Rate Me: http://spkr8.com/t/4511
  102. Questions?
  103. See ya!
  104. 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/

×