Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

High Performance JavaScript (CapitolJS 2011)

45,653 views

Published on

Published in: Technology, Education

High Performance JavaScript (CapitolJS 2011)

  1. High Performance JavaScript<br />Nicholas C. Zakas| CapitolJS | September 18, 2011<br />
  2. Who's this guy?<br />Co-Creator csslint.net<br />Contributor,<br />Creator of YUI Test<br />Ex-tech lead<br />Yahoo!<br />Author<br />Lead Author<br />Contributor<br />Lead Author<br />
  3. @slicknet<br />(complaints: @voodootikigod)<br />
  4. Does JavaScript performance matter?<br />
  5. All browsers now haveoptimizing JavaScript engines<br />Tracemonkey/<br />JaegarMonkey<br />(3.5+)<br />V8<br />(all)<br />Nitro<br />(4+)<br />Chakra<br />(9+)<br />Karakan<br />(10.5+)<br />
  6. http://ie.microsoft.com/testdrive/benchmarks/sunspider/default.html<br />
  7. Old computers ran slow applications<br />Small amounts of CPU power and memory<br />
  8. New computers are generally faster but<br />slow applications still exist<br />More CPU + more memory = less disciplined application development<br />
  9. Oh yeah, one more thing<br />
  10. It's still possible to write slow JavaScript<br />
  11. JavaScript performancedirectlyaffects user experience<br />
  12. The UI Threadaka Browser Event Loop<br />
  13. The browser UI thread is responsible for<br />both UI updates and JavaScript execution<br />Only one can happen at a time<br />
  14. Jobs for UI updates and JavaScript execution<br />are added to a UI queue<br />Each job must wait in line for its turn to execute<br />
  15. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><br /><script type="text/javascript"><br />window.onload = function(){<br /> document.getElementById("btn").onclick = function(){<br />//do something<br /> };<br />};<br /></script><br />
  16. Before Click<br />UI Thread<br />time<br />UI Queue<br />
  17. When Clicked<br />UI Thread<br />time<br />UI Queue<br />UI Update<br />onclick<br />UI Update<br />
  18. When Clicked<br />UI Thread<br />UI Update<br />time<br />UI Queue<br />onclick<br />Draw down state<br />UI Update<br />
  19. When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />UI Update<br />
  20. When Clicked<br />UI Thread<br />onclick<br />UI Update<br />UI Update<br />time<br />UI Queue<br />Draw up state<br />
  21. No UI updates while JavaScript is executing<br />
  22. JavaScript May Cause UI Update<br /><button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button><br /><script type="text/javascript"><br />window.onload = function(){<br /> document.getElementById("btn").onclick = function(){<br /> var div = document.createElement(“div”);<br /> div.className = “tip”;<br /> div.innerHTML = “You clicked me!”;<br /> document.body.appendChild(div);<br /> };<br />};<br /></script><br />
  23. A UI update must use the latest info available<br />
  24. Long-running JavaScript=Unresponsive UI<br />
  25. Responsive UI<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
  26. Unresponsive UI<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
  27. The longer JavaScript runs,the worse the user experience<br />
  28. The runaway script timer prevents JavaScript<br />from running for too long<br />Each browser imposes its own limit (except Opera)<br />
  29. Internet Explorer<br />
  30. Firefox<br />
  31. Safari<br />
  32. Chrome<br />
  33. Runaway Script Timer Limits<br />Internet Explorer: 5 million statements<br />Firefox: 10 seconds<br />Safari: 5 seconds<br />Chrome: Unknown, hooks into normal crash control mechanism<br />Opera: none<br />
  34. How Long Is Too Long?<br />“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.”<br />- Jakob Nielsen<br />
  35. Translation:No single JavaScript job should execute for more than 100ms to ensure a responsive UI<br />
  36. Recommendation:Limit JavaScript execution to no more than 50msmeasured on IE6 :)<br />
  37. Loadtime TechniquesDon't let JavaScript interfere with page load performance<br />
  38. During page load, JavaScript takes more time on the UI thread<br />
  39. <!doctype html><br /><html><br /><head><br /> <title>Example</title><br /></head><br /><body><br /> <p>Hello world!</p><br /><script src="foo.js"></script><br /> <p>See ya!</p><br /></body><br /></html><br />
  40. Result<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
  41. Result<br />UI Thread<br />foo.js<br />See ya!<br />Hello world!<br />time<br />
  42. Result<br />UI Thread<br />Download<br />See ya!<br />Hello world!<br />Parse<br />Run<br />time<br />The UI thread needs to wait for the script to<br />download, parse, and run before continuing<br />
  43. Result<br />UI Thread<br />Download<br />See ya!<br />Hello world!<br />Parse<br />Run<br />Variable<br />Constant<br />Download time takes the longest and is variable<br />
  44. Translation:The page doesn't render while JavaScript is downloading, parsing, or executing during page load<br />
  45. <!doctype html><br /><html><br /><head><br /> <title>Example</title><br /></head><br /><body><br /><script src="foo.js"></script><br /> <p>Hello world!</p><br /><script src="bar.js"></script><br /> <p>See ya!</p><br /><script src="baz.js"></script><br /> <p>Uh oh!</p><br /></body><br /></html><br />
  46. Result<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />JavaScript<br />JavaScript<br />time<br />The more scripts to download in between UI<br />updates, the longer the page takes to render<br />
  47. Technique #1: Load scripts dynamically<br />
  48. Basic Technique<br />var script = document.createElement("script"),<br /> body;<br />script.type = "text/javascript";<br />script.src = "foo.js";<br />body.insertBefore(script, body.firstChild);<br />Dynamically loaded scripts are non-blocking<br />
  49. Downloads no longer block the UI thread<br />
  50. <!doctype html><br /><html><br /><head><br /> <title>Example</title><br /></head><br /><body><br /> <p>Hello world!</p><br /><script src="foo.js"></script><br /> <p>See ya!</p><br /></body><br /></html><br />
  51. Using HTML <script><br />UI Thread<br />Download<br />See ya!<br />Hello world!<br />Parse<br />Run<br />time<br />
  52. <!doctype html><br /><html><br /><head><br /> <title>Example</title><br /></head><br /><body><br /> <p>Hello world!</p><br /> <script><br /> var script = document.createElement("script"),<br /> body = document.body;<br /> script.type = "text/javascript";<br /> script.src = "foo.js";<br /> body.insertBefore(script, body.firstChild);<br /> </script><br /> <p>See ya!</p><!-- more content --><br /></body><br /></html><br />
  53. Using Dynamic Scripts<br />UI Thread<br />See ya!<br />Hello world!<br />UI Update<br />Run<br />time<br />Download<br />Parse<br />Only code execution happens on the UI thread,<br />which means less blocking of UI updates<br />
  54. function loadScript(url, callback){var script = document.createElement("script"), body = document.body;script.type = "text/javascript";<br />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);<br />}<br />
  55. Usage<br />loadScript("foo.js", function(){<br /> alert("Loaded!");<br />});<br />
  56. Timing Note:Script execution begins immediately after download and parse – timing of execution is not guaranteed<br />
  57. Technique #2: Defer scripts<br />
  58. <!doctype html><br /><html><br /><head><br /> <title>Example</title><br /></head><br /><body><br /> <p>Hello world!</p><br /><script defer src="foo.js"></script><br /> <p>See ya!</p><br /> <!-- even more markup --><br /></body><br /></html><br />
  59. Support for <script defer><br />?<br />5.0<br />3.5<br />7.0<br />4.0<br />
  60. Deferred scripts begin to download immediately, but don't execute until all UI updates complete<br />
  61. Using <script defer><br />UI Thread<br />See ya!<br />Hello world!<br />More UI<br />Run<br />More UI<br />time<br />Download<br />Parse<br />Similar to dynamic script nodes, but with a<br />guarantee that execution will happen last<br />
  62. Timing Note:Although scripts always execute after UI updates complete, the order of multiple <script defer> scripts is not guaranteed across browsers<br />
  63. Technique #3: Asynchronous scripts<br />
  64. <!doctype html><br /><html><br /><head><br /> <title>Example</title><br /></head><br /><body><br /> <p>Hello world!</p><br /><script async src="foo.js"></script><br /> <p>See ya!</p><br /> <!-- even more markup --><br /></body><br /></html><br />
  65. Support for <script async><br />?<br />5.0<br />3.6<br />7.0<br />10<br />
  66. Asynchronous scripts behave a lot like dynamic scripts<br />
  67. Using <script async><br />UI Thread<br />See ya!<br />Hello world!<br />UI Update<br />Run<br />time<br />Download<br />Parse<br />Download begins immediately and execution is<br />slotted in at first available spot<br />
  68. Note:Order of execution is explicitly not preserved for asynchronous scripts<br />
  69. Runtime TechniquesWays to ensure JavaScript doesn't run away<br />
  70. function processArray(items, process, callback){<br />for (var i=0,len=items.length; i < len; i++){<br /> process(items[i]);<br /> }<br /> callback();<br />}<br />
  71. Technique #1: Timers<br />
  72. //create a new timer and delay by 500ms<br />setTimeout(function(){<br />//code to execute here<br />}, 500);<br />setTimeout() schedules a function to be added to the UI queue after a delay<br />
  73. function timedProcessArray(items, process, callback){<br />//create a clone of the original var todo = items.concat();<br /> setTimeout(function(){<br />var start = +new Date();<br />do {<br /> process(todo.shift());<br /> } while (todo.length > 0 &&<br /> (+new Date() - start < 50));<br />if (todo.length > 0){<br /> setTimeout(arguments.callee, 25);<br /> } else {<br /> callback(items);<br /> }<br /> }, 25);<br />}<br />
  74. When Clicked<br />UI Thread<br />time<br />UI Queue<br />UI Update<br />onclick<br />UI Update<br />
  75. When Clicked<br />UI Thread<br />UI Update<br />time<br />UI Queue<br />onclick<br />UI Update<br />
  76. When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />UI Update<br />
  77. When Clicked<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
  78. After 25ms<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />JavaScript<br />
  79. After 25ms<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
  80. After Another 25ms<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />JavaScript<br />
  81. After Another 25ms<br />UI Thread<br />JavaScript<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
  82. Technique #2: Script Yielding<br />NEW!<br />
  83. //delay a function until after UI updates are done<br />setImmediate(function(){<br />//code to execute here<br />});<br />setImmediate() adds code to the UI queue after pending UI updates are finished<br />
  84. Support for Script Yielding<br />?<br />?<br />?<br />?<br />10<br />msSetIntermediate()<br />
  85. functionyieldingProcessArray(items, process, callback){<br />//create a clone of the originalvartodo = items.concat();<br />setImmediate(function(){<br />var start = +new Date();<br />do {<br /> process(todo.shift());<br /> } while (todo.length > 0 &&<br /> (+new Date() - start < 50));<br />if (todo.length > 0){<br />setImmediate(arguments.callee);<br /> } else {<br /> callback(items);<br /> }<br />});<br />}<br />
  86. When Clicked<br />UI Thread<br />time<br />UI Queue<br />UI Update<br />onclick<br />UI Update<br />
  87. When Clicked<br />UI Thread<br />UI Update<br />time<br />UI Queue<br />onclick<br />UI Update<br />
  88. When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />UI Update<br />
  89. When Clicked<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
  90. After Last UI Update<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />JavaScript<br />
  91. After Last UI Update<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
  92. No Other UI Updates<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />JavaScript<br />
  93. No Other UI Updates<br />UI Thread<br />JavaScript<br />JavaScript<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
  94. Technique #3: Web Workers<br />
  95. Support for Web Workers<br />10.6<br />4.0<br />3.5<br />4.0<br />10<br />
  96. Web Workers<br />Asynchronous JavaScript execution<br />Execution happens outside the UI thread<br />Doesn’t block UI updates<br />Data-Driven API<br />Data is serialized going into and out of the worker<br />No access to DOM or BOM<br />Separate execution environment<br />
  97. //in page<br />var worker = new Worker("process.js");<br />worker.onmessage = function(event){<br /> useData(event.data);<br />};<br />worker.postMessage(values);<br />//in process.js<br />self.onmessage = function(event){<br />var items = event.data;<br />for (var i=0,len=items.length; i < len; i++){<br /> process(items[i]);<br /> }<br /> self.postMessage(items);<br />};<br />
  98. When Clicked<br />UI Thread<br />time<br />UI Queue<br />UI Update<br />onclick<br />UI Update<br />
  99. When Clicked<br />UI Thread<br />UI Update<br />time<br />UI Queue<br />onclick<br />UI Update<br />
  100. When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />UI Update<br />
  101. When Clicked<br />UI Thread<br />onclick<br />UI Update<br />time<br />UI Queue<br />Worker Thread<br />UI Update<br />
  102. When Clicked<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />Worker Thread<br />JavaScript<br />
  103. Worker Thread Complete<br />UI Thread<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />onmessage<br />
  104. Worker Thread Complete<br />UI Thread<br />onmessage<br />UI Update<br />UI Update<br />onclick<br />time<br />UI Queue<br />
  105. Recap<br />
  106. The browser UI thread is responsible for<br />both UI updates and JavaScript execution<br />Only one can happen at a time<br />
  107. Responsive UI<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
  108. Unresponsive UI<br />UI Thread<br />JavaScript<br />UI Update<br />UI Update<br />time<br />
  109. Avoid Slow Loading JavaScript<br />Dynamically created scripts<br />Deferred scripts<br />Asynchronous scripts<br />
  110. Avoid Slow JavaScript<br />Don't allow JavaScript to execute for more than 50ms<br />Break up long JavaScript processes using:<br />Timers<br />Script Yielding (future)<br />Web Workers<br />
  111. Etcetera<br />My blog: www.nczonline.net<br />Twitter: @slicknet<br />These Slides: slideshare.net/nzakas<br />Hire us: projects@stubbornella.org<br />
  112. Questions?<br />
  113. Creative Commons Images Used<br />http://www.flickr.com/photos/lrargerich/3115367361/<br />http://www.flickr.com/photos/hippie/2406411610/<br />http://www.flickr.com/photos/55733754@N00/3325000738/<br />http://www.flickr.com/photos/eurleif/255241547/<br />http://www.flickr.com/photos/off_the_wall/3444915939/<br />http://www.flickr.com/photos/wwarby/3296379139/<br />http://www.flickr.com/photos/derekgavey/4358797365/<br />http://www.flickr.com/photos/mulad/286641998/<br />http://www.flickr.com/photos/torley/2361164281/<br />http://www.flickr.com/photos/ottoman42/455242/<br />http://www.flickr.com/photos/goincase/3843348908/<br />

×