Your SlideShare is downloading. ×
0
High Performance JavaScript
                                   Nicholas C. Zakas
                Principal Front End Engin...
Principal Front End Engineer
Contributor
Author
Things I Know About
                                  JavaScript
                   Professional
                    Wrest...
Does this matter?
Old computers ran slow applications
     Small amounts of CPU power and memory
New computers are generally faster but
       slow applications still exist
More CPU + more memory = less disciplined appl...
It's still possible to write slow
JavaScript on the new, faster
       JavaScript engines
How can I improve JavaScript
       performance?
How can I improve JavaScript
       performance?
How can I make this fast???
How can I improve JavaScript
       performance?
How can I make this fast???

  Why is this so slow?????
Many aspects conspire to make JavaScript slow
           Awareness is the first step to solution
The UI Thread
The brains of the operation
The browser UI thread is responsible for
both UI updates and JavaScript execution
           Only one can happen at a time
Jobs for UI updates and JavaScript execution are
  added to a UI queue if the UI thread is busy
         Each job must wai...
<button id="btn" style="font-size: 30px; padding: 0.5em
    1em">Click Me</button>

<script type="text/javascript">
$(docu...
Before Click

UI Thread



time
                           UI Queue
When Clicked

UI Thread



time
                           UI Queue

                             UI Update

             ...
When Clicked

UI Thread

 UI Update

time
                                   UI Queue

                                   ...
When Clicked

UI Thread

 UI Update   onclick

time
                              UI Queue

                              ...
When Clicked

UI Thread

 UI Update   onclick       UI Update

time
                                       UI Queue


    ...
No UI updates while JavaScript is
          executing!
JavaScript May Cause UI Update
<button id="btn" style="font-size: 30px; padding: 0.5em
    1em">Click Me</button>

<script...
A UI update must use the latest
        info available
Long-running JavaScript
          =
   Unresponsive UI
Responsive UI

UI Thread

 UI Update   JavaScript   UI Update

time
Unresponsive UI

UI Thread

 UI Update       JavaScript    UI Update

time
The runaway script timer prevents JavaScript
         from running for too long
      Each browser imposes its own limit (...
Internet Explorer
Firefox
Safari
Chrome
Runaway Script Timer Limits
• Internet Explorer: 5 million statements
• Firefox: 10 seconds
• Safari: 5 seconds
• Chrome: ...
How Long Is Too Long?
“0.1 second [100ms] is about the limit for
having the user feel that the system is reacting
instanta...
Translation:
 No single JavaScript job should
execute for more than 100ms to
     ensure a responsive UI
Recommendation:
Limit JavaScript execution to no more
              than 50ms
function processArray(items, process, callback){
    for (var i=0,len=items.length; i < len; i++){
        process(items[i...
Timers to the rescue!
JavaScript Timers
• Created using setTimeout()
• Schedules a new JavaScript execution job for
  some time in the future
• ...
JavaScript Timers
• For complex processing, split up into timed
  functionality
• Use timers to delay some processing for ...
function timedProcessArray(items, process, callback){
    //create a clone of the original
       var todo = items.concat(...
When Clicked

UI Thread



time
                           UI Queue

                             UI Update

             ...
When Clicked

UI Thread

 UI Update

time
                            UI Queue

                              onclick

   ...
When Clicked

UI Thread

 UI Update   onclick




time
                                  UI Queue

                       ...
When Clicked

UI Thread

 UI Update   onclick   UI Update

time
                                   UI Queue
After 25ms

UI Thread

 UI Update   onclick   UI Update

time
                                    UI Queue

              ...
After 25ms

UI Thread

 UI Update   onclick   UI Update   JavaScript




time
                                            ...
After Another 25ms

UI Thread

 UI Update   onclick   UI Update   JavaScript




time
                                    ...
After Another 25ms

UI Thread

 UI Update   onclick   UI Update   JavaScript         JavaScript




time
                 ...
Web Workers to the rescue!
Web Workers
• Asynchronous JavaScript execution
• Execution happens in a separate process
   – Not on the UI thread = no U...
//in page
var worker = new Worker("process.js");
worker.onmessage = function(event){
     useData(event.data);
};
worker.p...
When Clicked

UI Thread



time
                           UI Queue

                             UI Update

             ...
When Clicked

UI Thread

 UI Update

time
                            UI Queue

                              onclick

   ...
When Clicked

UI Thread

 UI Update   onclick




time
                                  UI Queue

                       ...
When Clicked

UI Thread

 UI Update   onclick




time

             Worker Thread        UI Queue

                      ...
When Clicked

UI Thread

 UI Update   onclick       UI Update

time

             Worker Thread             UI Queue

    ...
Worker Thread Complete

UI Thread

 UI Update    onclick   UI Update

time
                                    UI Queue

 ...
Worker Thread Complete

UI Thread

 UI Update    onclick   UI Update   onmessage




time
                                ...
Web Workers Support




3.5      4.0        4.0
Repaint and Reflow
     UI update jobs
Long UI updates
       =
Unresponsive UI
Unresponsive UI

UI Thread

 UI Update   JavaScript   UI Update

time
Long UI updates
       =
Unresponsive UI
       =
Frustrated users
JavaScript can cause
  long UI updates
A repaint occurs when a visual change doesn't
        require recalculation of layout
 Changes to visibility, colors (text...
Repaint
<button id="btn" style="font-size: 30px; padding: 0.5em
    1em">Click Me</button>

<script type="text/javascript"...
A reflow occurs when a visual change
              requires a change in layout
Initial page load ▪ browser resize ▪ DOM st...
Reflow
<button id="btn" style="font-size: 30px; padding: 0.5em
    1em">Click Me</button>

<script type="text/javascript">...
Repaints and reflows are queued
   up as JavaScript executes
Reflow


var list = $("ul.items");

for (var i=0; i < 10; i++){
    list.append("<li>Item #" + i + "</li>");
}


         ...
Limiting repaints/reflows
improves overall performance
Solution #1
Perform DOM manipulations
       off-document
Off-Document Operations
• Fast because there's no repaint/reflow
• Techniques:
   – Remove element from the document, make...
DocumentFragment
• A document-like object
• Not visually represented
• Considered to be owned by the document from
  which...
No
      reflow!


Reflow!
Solution #2
Group Style Changes
Repaint!           Reflow!

$("span.example").css({   color: "red" });
$("span.example").css({   height: "100px" });
     ...
Grouping Style Changes

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

$...
Grouping Style Changes



var item = document.getElementById("myItem");
item.style.cssText = "color:red;height:100px;" +
 ...
Solution #3
Avoid Accidental Reflow
Accidental Reflow



$("div.example").css({ width: "100px"});

var width = $("div.example").width();


                   ...
What to do?
• Minimize access to layout information
  –   offsetTop, offsetLeft, offsetWidth, offsetHeight
  –   scrollTop...
Recap
Things I Know About
                                  JavaScript
                   Professional
                    Wrest...
The browser UI thread is responsible for
both UI updates and JavaScript execution
           Only one can happen at a time
Responsive UI

UI Thread

 UI Update   JavaScript   UI Update

time
Unresponsive UI

UI Thread

 UI Update       JavaScript    UI Update

time
Unresponsive UI

UI Thread

 UI Update   JavaScript   UI Update

time
Avoid Slow JavaScript
• Don't allow JavaScript to execute for more
  than 50ms
• Break up long JavaScript processes using:...
Avoid Long UI Updates
• Be careful of repaint and reflow
• Perform complex DOM operations off-
  document
   – Remove elem...
Questions?
Etcetera
• My blog:    www.nczonline.net
• My email:   nzakas@yahoo-inc.com
• Twitter:    @slicknet
Creative Commons Images Used
•   http://www.flickr.com/photos/lrargerich/3115367361/
•   http://www.flickr.com/photos/phot...
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
Upcoming SlideShare
Loading in...5
×

High Performance JavaScript - jQuery Conference SF Bay Area 2010

13,145

Published on

Learn the inner workings of JavaScript to learn what makes things slow and how to speed them up. Heavily focused on DOM manipulation and UI updates.

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

No Downloads
Views
Total Views
13,145
On Slideshare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
468
Comments
0
Likes
56
Embeds 0
No embeds

No notes for slide
  • Over the past couple of years, we&apos;ve seen JavaScript development earn recognition as a true discipline. The idea that you should architect your code, use patterns and good programming practices has really elevated the role of the front end engineer. In my opinion, part of this elevation has been the adoption of what has traditionally been considered back end methodologies. We now focus on performance and algorithms, there&apos;s unit testing for JavaScript, and so much more. One of the areas that I&apos;ve seen a much slower than adoption that I&apos;d like is in the area of error handling. How many people have an error handling strategy for their backend? How many have dashboards that display problems with uptime and performance? How many have anything similar for the front end? Typically, the front end has been this black hole of information. You may get a few customer reports here and there, but you have no information about what&apos;s going on, how often it&apos;s occurring, or how many people have been affected.
  • So what have we talked about? Maintainable JavaScript is made up of four components. First is Code Conventions that describe the format of the code you’re writing. Second is Loose Coupling – keeping HTML, JavaScript, and CSS on separate layers and keeping application logic out of event handlers. Third is Programming Practices that ensure your code is readable and easily debugged. Fourth is creating a Build Process
  • Transcript of "High Performance JavaScript - jQuery Conference SF Bay Area 2010"

    1. 1. High Performance JavaScript Nicholas C. Zakas Principal Front End Engineer, Yahoo! jQuery Conference – SF Bay Area, April 24 2010
    2. 2. Principal Front End Engineer
    3. 3. Contributor
    4. 4. Author
    5. 5. Things I Know About JavaScript Professional Wrestling YUI jQuery
    6. 6. Does this matter?
    7. 7. Old computers ran slow applications Small amounts of CPU power and memory
    8. 8. New computers are generally faster but slow applications still exist More CPU + more memory = less disciplined application development
    9. 9. It's still possible to write slow JavaScript on the new, faster JavaScript engines
    10. 10. How can I improve JavaScript performance?
    11. 11. How can I improve JavaScript performance? How can I make this fast???
    12. 12. How can I improve JavaScript performance? How can I make this fast??? Why is this so slow?????
    13. 13. Many aspects conspire to make JavaScript slow Awareness is the first step to solution
    14. 14. The UI Thread The brains of the operation
    15. 15. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
    16. 16. 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
    17. 17. <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> $(document).ready(function(){ $("#btn").bind("click",function(){ //do something }); }); </script>
    18. 18. Before Click UI Thread time UI Queue
    19. 19. When Clicked UI Thread time UI Queue UI Update onclick UI Update
    20. 20. When Clicked UI Thread UI Update time UI Queue onclick Draw down state UI Update
    21. 21. When Clicked UI Thread UI Update onclick time UI Queue UI Update
    22. 22. When Clicked UI Thread UI Update onclick UI Update time UI Queue Draw up state
    23. 23. No UI updates while JavaScript is executing!
    24. 24. JavaScript May Cause UI Update <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> $(document).ready(function(){ $("#btn").bind("click",function(){ $("body").append("<div class="tip">You " + "clicked me!</div>”); }); }); </script>
    25. 25. A UI update must use the latest info available
    26. 26. Long-running JavaScript = Unresponsive UI
    27. 27. Responsive UI UI Thread UI Update JavaScript UI Update time
    28. 28. Unresponsive UI UI Thread UI Update JavaScript UI Update time
    29. 29. The runaway script timer prevents JavaScript from running for too long Each browser imposes its own limit (except Opera)
    30. 30. Internet Explorer
    31. 31. Firefox
    32. 32. Safari
    33. 33. Chrome
    34. 34. 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
    35. 35. 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
    36. 36. Translation: No single JavaScript job should execute for more than 100ms to ensure a responsive UI
    37. 37. Recommendation: Limit JavaScript execution to no more than 50ms
    38. 38. function processArray(items, process, callback){ for (var i=0,len=items.length; i < len; i++){ process(items[i]); } callback(); }
    39. 39. Timers to the rescue!
    40. 40. JavaScript Timers • Created using setTimeout() • Schedules a new JavaScript execution job for some time in the future • When the delay is up, the job is added to the UI queue – Note: This does not guarantee execution after the delay, just that the job is added to the UI queue and will be executed when appropriate
    41. 41. JavaScript Timers • For complex processing, split up into timed functionality • Use timers to delay some processing for later
    42. 42. 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); }
    43. 43. When Clicked UI Thread time UI Queue UI Update onclick UI Update
    44. 44. When Clicked UI Thread UI Update time UI Queue onclick UI Update
    45. 45. When Clicked UI Thread UI Update onclick time UI Queue UI Update
    46. 46. When Clicked UI Thread UI Update onclick UI Update time UI Queue
    47. 47. After 25ms UI Thread UI Update onclick UI Update time UI Queue JavaScript
    48. 48. After 25ms UI Thread UI Update onclick UI Update JavaScript time UI Queue
    49. 49. After Another 25ms UI Thread UI Update onclick UI Update JavaScript time UI Queue JavaScript
    50. 50. After Another 25ms UI Thread UI Update onclick UI Update JavaScript JavaScript time UI Queue
    51. 51. Web Workers to the rescue!
    52. 52. Web Workers • Asynchronous JavaScript execution • Execution happens in a separate process – 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
    53. 53. //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); };
    54. 54. When Clicked UI Thread time UI Queue UI Update onclick UI Update
    55. 55. When Clicked UI Thread UI Update time UI Queue onclick UI Update
    56. 56. When Clicked UI Thread UI Update onclick time UI Queue UI Update
    57. 57. When Clicked UI Thread UI Update onclick time Worker Thread UI Queue UI Update
    58. 58. When Clicked UI Thread UI Update onclick UI Update time Worker Thread UI Queue JavaScript
    59. 59. Worker Thread Complete UI Thread UI Update onclick UI Update time UI Queue onmessage
    60. 60. Worker Thread Complete UI Thread UI Update onclick UI Update onmessage time UI Queue
    61. 61. Web Workers Support 3.5 4.0 4.0
    62. 62. Repaint and Reflow UI update jobs
    63. 63. Long UI updates = Unresponsive UI
    64. 64. Unresponsive UI UI Thread UI Update JavaScript UI Update time
    65. 65. Long UI updates = Unresponsive UI = Frustrated users
    66. 66. JavaScript can cause long UI updates
    67. 67. A repaint occurs when a visual change doesn't require recalculation of layout Changes to visibility, colors (text/background), background images, etc.
    68. 68. Repaint <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> $(document).ready(function(){ $("#btn").bind("click",function(){ $(this).css({ color: "#f00" }); }); }); </script> Repaint!
    69. 69. 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
    70. 70. Reflow <button id="btn" style="font-size: 30px; padding: 0.5em 1em">Click Me</button> <script type="text/javascript"> $(document).ready(function(){ $("#btn").bind("click",function(){ $("body").append("<div class="tip">You " + "clicked me!</div>”); }); }); </script> Reflow!
    71. 71. Repaints and reflows are queued up as JavaScript executes
    72. 72. Reflow var list = $("ul.items"); for (var i=0; i < 10; i++){ list.append("<li>Item #" + i + "</li>"); } Reflow x 10!
    73. 73. Limiting repaints/reflows improves overall performance
    74. 74. Solution #1 Perform DOM manipulations off-document
    75. 75. 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
    76. 76. 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
    77. 77. No reflow! Reflow!
    78. 78. Solution #2 Group Style Changes
    79. 79. Repaint! Reflow! $("span.example").css({ color: "red" }); $("span.example").css({ height: "100px" }); Reflow! $("span.example").css({ fontSize: "25px" }); $("span.example").css({ backgroundColor: "white" }); Repaint!
    80. 80. Grouping Style Changes .active { color: red; height: 100px; fontSize: 25px; background-color: white; } $("span.example").addClass("active"); Reflow!
    81. 81. Grouping Style Changes var item = document.getElementById("myItem"); item.style.cssText = "color:red;height:100px;" + "font-size:25px;background-color: white"); Reflow!
    82. 82. Solution #3 Avoid Accidental Reflow
    83. 83. Accidental Reflow $("div.example").css({ width: "100px"}); var width = $("div.example").width(); Reflow!
    84. 84. 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
    85. 85. Recap
    86. 86. Things I Know About JavaScript Professional Wrestling YUI jQuery
    87. 87. The browser UI thread is responsible for both UI updates and JavaScript execution Only one can happen at a time
    88. 88. Responsive UI UI Thread UI Update JavaScript UI Update time
    89. 89. Unresponsive UI UI Thread UI Update JavaScript UI Update time
    90. 90. Unresponsive UI UI Thread UI Update JavaScript UI Update time
    91. 91. Avoid Slow JavaScript • Don't allow JavaScript to execute for more than 50ms • Break up long JavaScript processes using: – Timers – Web Workers
    92. 92. 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
    93. 93. Questions?
    94. 94. Etcetera • My blog: www.nczonline.net • My email: nzakas@yahoo-inc.com • Twitter: @slicknet
    95. 95. Creative Commons Images Used • http://www.flickr.com/photos/lrargerich/3115367361/ • http://www.flickr.com/photos/photomonkey/93277011/ • 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/
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×