Download presentation
Presentation is loading. Please wait.
Published byBertram Evans Modified over 8 years ago
2
John Lawrimore, 2014 JavaScript Performance
3
Presenter JOHN LAWRIMORE john.lawrimore@improvingenterprises.com @johnlawrimore - Principal Consultant at Improving Enterprises - Microsoft enthusiast - Background heavy in web applications development - Unable to think of interesting things to say about self
4
Access this Presentation Online http://johnlawrimore.com/jsperformance
5
Objectives 1.Provide a better understanding of how JavaScript works 2.Introduce practices and techniques that will noticeably increase performance 3.Focus ONLY on what... Generally applies to all browsers You can reasonably begin implementing tomorrow
6
Approaching Optimization The right optimization strategy will differ by application Do what makes sense Pick your battles Consider maintainability Challenge your assumptions regularly
7
What is scope chain?
8
Scope Chain
10
Namespacing Condenses the global namespace Reduces search time for its descendants HINT: Set distant namespaces to a variable to reduce search time
11
Closures (anonymous functions) Pros: Access to variables outside the function Cons: Adds to the scope chain Requires a new execution context
12
What’s wrong with this?
14
With and Try-Catch Use Try-Catch sparingly And NEVER try catch in a loop! NEVER use With !
15
What’s missing?
16
Local variables missing the var keyword are automatically instantiated in the global namespace!! ! What’s missing?
17
Managing Scope Don’t use the global namespace! Cache out-of-scope variables referenced more than once Limit augmentations to the scope chain Closures With Try Catch Consider scope when creating prototypes Don’t forget to use ‘var’
18
What is the DOM?
19
Document Object Model
20
Under the hood
21
What impacts DOM performance?
22
DOM Performance Issues DOM search DOM manipulation !!
23
What’s wrong with this?
24
THE DOM IS NOT A DATABASE! ! What’s wrong with this?
25
Data Property Maintained within the JavaScript engine (not the DOM) Can be global or bound to a specific element
26
Data vs. Attributes Attribute StorageData Property Avoids hits to the DOM Accommodates types, arrays and complex objects Optimized by built-in caching Maintains valid HTML
27
Data vs. Attributes
28
What is Reflow/Repaint?
29
Repaint vs. Reflow REPAINT Visual changes that do not alter the document layout. (aka: redraw) Examples: Color Font style REFLOW Occurs when a visual change is made to the HTML document that requires layout to be computed. Examples: Initial render Browser window resize Visible elements added or removed Element position changes Changes in size, margin, border, etc. Text changes Layout information is retrieved (in some cases)
30
Repaint vs. Reflow Both are expensive in terms of performance because they require traversing Reflow may or may not affect the entire document JavaScript engines attempt to perform reflow in batches
31
Let’s improve this!
35
DocumentFragment Child of the document that created it No visual representation Construct happens behind the scenes When passed to appended to document, only its children are added
36
CSS Transitions > Animation Allows property changes in CSS values to occur smoothly over a specified duration. Powerful, clean, and faster than JS animations Not supported in IE 9 and earlier
37
Avoiding Reflow Group styles whenever possible Use classes or cssText instead of styles Accumulate new elements and append with one call innerHTML (or html() for jQuery) documentFragment Temporarily remove elements to be modified from the document remove(), detach(), etc. Avoid animation, and leverage libraries or CSS transitions when you must
38
What is the outcome of this method?
39
IT NEVER ENDS! !
40
HtmlCollections Don’t let them fool you! They are not arrays! Examples: document.getElementsByTagName document.getElemenetsByClassName document.images document.forms
41
Let’s improve this!
42
Only touch the HTMLCollection one time
43
Reducing DOM Interaction Never store data on the DOM Avoid reflow Limit calls to HtmlCollections
44
UI Thread Responsibilities Draw UI Execute JavaScript ! UI THREAD CAN ONLY DO ONE RESPONSIBILITY AT A TIME
45
Timers Run secondary tasks in the back ground AFTER the page has loaded. When timer is done, job is added to the UI Queue. Remember that less timers with more work is better than more timers with less work.
46
Web Workers New option for asynchronous execution in HTML5 Operates outside of UI Thread Trigger specified event handlers when completed
47
What loop should I use?
48
Loops for for-in for-each [].forEach() $().each() do-while while
49
Selecting a Loop Avoid non-native function based loops Creates closures (and associated overhead) in scope chain Takes about 8-10x as long as basic for loop Avoid for-in and for-each for-in performs expensive type evaluation for-each deprecated in ECMA -357
50
Selecting a Loop What matters? Amount of work being performed Number of iterations Do Less Work!! Avoid lookups inside loop Reduce number of calculation being performed
51
How can this be improved?
52
Combine control condition and control variable into a single statement How can this be improved? BETTER!
53
Combine the terminal condition evaluation w/ incrementing / decrementing How can this be improved? BETTER! BEST!
54
Switch or If-Then-Else?
55
Selecting a Conditional Statement It Depends! As conditions increase, switch becomes more and more optimal
56
Let’s improve this!
57
BETTER! Consider a combined approach!
58
Let’s improve this! BETTER! Create a hash table OR EVEN
59
Common Pitfalls
60
What’s wrong here?
62
MEMORY LEAK! !
63
What’s wrong here? MEMORY LEAK! ! Break the chain!
64
What’s wrong here?
65
WILL BE CALLED WAY TOO MUCH! !
66
Throttle and Debounce Throttling limits the execution of a function to no more than once every delay milliseconds Debouncing guarantees that the function will only ever be executed a single time (given a specified threshold).
67
Smarter Coding
68
Which is better?
69
BETTER! Use literals, avoid ‘new’
70
Which way is better?
71
Use prototypes!
72
Reuse/Recycle Reuse old variables instead of creating new ones!
73
Event Delegation Handle array element events with a single binding on the container Events to bubble up the DOM tree Detect the node originating the event and act accordingly Use stopPropagation(), preventDefaults(), etc. as needed
74
Let’s improve this!
75
BETTER! Use lazy loading
76
String Manipulation Use += over function based concatenation Use regexes to parse and slice
77
Which is faster?
78
BETTER! Use bitwise operators where appropriate
79
Traversing Always use the most optimum methods for crawling the DOM DOM properties such as childNode, firstChild, nextSibling, etc. don’t distinguish between element and other node types (such as spaces, comments, etc.)
80
JSON eval() SLOW! Libraries EVEN WORSE! Always use the JSON namespace Native in all modern browsers (IE8+) JSON.parse() JSON.stringify() toJSON() prototype !
81
Are libraries efficient?
82
Using Libraries The most optimal library is no match to the JavaScript Engine! Intermediaries come with overhead Native methods are compiled machine code Leverage libraries only in cases where value is added…
83
Use native features over libraries indexOf() lastIndexOf() every() filter() forEach() map() some()
84
querySelectorAll() Much faster than using JavaScript and DOM to iterate and narrow down a list of elements Supported in IE8+
85
What selector should I use?
86
Selectors All selectors are NOT created equal Always consider what is going on under the covers! TypeExample Universal * Type div ID #header Class.promo Attribute [type=“text”] Pseudo-class a:hover Adjacent sibling h2 + p Child li > ul Descendant ul a
87
ID & Element Selectors $(‘#Element, form, input’) Most optimal choice! Backed by native DOM operations eg. getElementById()
88
Class Selectors $(‘.element’) Much slower selector Particularly in browsers where getElementsByClassName() is not supported !
89
Pseudo & Attribute $(‘:visible, :hidden’); $(‘[attribute=value]’); USE SPARINGLY No native calls available querySelector() and querySelectorAll() help in modern browsers !
90
Combining Selectors Selector engines use the Right to Left Model Always make your MOST SPECIFIC selector on the right
91
Let’s rank these! A. $('.child', $('#parent')) B. $(‘#parent >.child’) C. $parent.find(‘.child’) D. $(‘#parent.child’) E. $(‘.child’, $parent) F. $parent.children(".child’)
92
Let’s rank these! D. $(‘#parent.child’) B. $(‘#parent >.child’) F. $parent.children(".child’) A. $('.child', $('#parent')) E. $(‘.child’, $parent) C. $parent.find(‘.child’) RESULTS:
93
Can Script Tags Hurt Performance?
94
Script Tags PROBLEMS External references result in an http request Inline scripts circumvent client-side caching
95
Load Script Tags Faster ALWAYS "minify" production code! Bundle scripts (and styles) into single resources Leverage Code Delivery Networks (CDN) Lazy load scripts with AMD utilities
96
AMD Asynchronous Module Definition Example: require.js
97
How do I Test Performance?
98
jsPerf Compare the performance of code snippets across browsers
99
YSlow Grade your site’s optimizations
100
Reading Material High Performance JavaScript Nicholas C. Zakas
101
Questions? john.lawrimore@improvingenterprises.com http://linkedin.com/in/johnlawrimore
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.