Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Improving JavaScript Performance

No description
by

John Lawrimore

on 17 September 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Improving JavaScript Performance

Reflow:
The process by which the geometry of the layout engines formatting objects are computed.



Reflow occurs when:
Initial render
Visible DOM elements are added or removed
Elements change position
Elements change size, padding, border, etc.
Content is changed
Browser window resize
Layout information is retrieved (in some cases)
Compare the performance of code snippets
across different browsers
jsPerf
ALWAYS "minify" production code!

Leverage Code Delivery Networks (CDN)
Google Hosted Library

Consider "lazy loading" utilities
Asynchronous Module Definition (AMD)
Load Scripts Faster
In most browsers, script tags are loaded synchronously
Could block the page from continuing when placed at top of page
NOTE: Progressive rendering optimization on some browsers have helped to alleviate the problem

Consider:
Leveraging the defer option for scripts not modifying the DOM
Leveraging the async option
Script Tags
External references result in an http request
Inline scripts circumvent client-side caching

Solution?
Group scripts (and styles) to minimize the number tags on a page
Script Tags
$(‘:visible, :hidden’);
$(‘[attribute=value]’);

Slowest options available
No native calls available
querySelector() and querySelectorAll() help in modern browsers
Pseudo & Attribute
$(‘.element’)

Typically slower selector
Particularly in browsers where getElementsByClassName() is not supported
Class Selectors
$(‘#Element, form, input’)

Most optimal choice!

Backed by native DOM operations
eg. getElementById()
ID & Element Selectors
$parent.find(‘.child’)

Rating:
100% optimized

Behind the scenes:
Is able to directly call native getElementById, getElementsByName, and getElementsByTagName without narrowing scope or translating.
Selecting the
Right Selector
$(‘.child’, $parent)

Rating:
90% optimized

Behind the scenes:
Scope is quickly parsed and translated into $.parent.find(‘child’)
Selecting the
Right Selector
$('.child', $('#parent'))

Rating:
75% optimized

Behind the scenes:
Equivalent internally to $(‘#parent’).find(‘.child’), note the parent is a jQuery object which causes additional overhead
Selecting the
Right Selector
$parent.children(".child’)

Rating:
50% optimized

Behind the scenes:
Must rely on $.sibling and nextSibling() to find nodes following other nodes along the same tree
Selecting the
Right Selector
$(‘#parent > .child’)

Rating:
30% optimized

Behind the scenes:
While selecting by child is more efficient than selecting by descendant, the right of the combinator is still less specific than the left.
Selecting the
Right Selector
$(‘#parent .child’)

Rating:
25% optimized

Behind the scenes:
Since the selector engine reads right to left, the less specific selector is resolved first using a class selector. The descendant selector must translate to .find() to complete the resolution.
Selecting the
Right Selector

Types of Selectors
Chaining is more efficient than caching the selector. (and more readable!)
Method Chaining
eval() SLOW!
Libraries EVEN WORSE!

JSON namespace
Native in all modern browsers (IE8+)
JSON.parse()
JSON.stringify()
toJSON() prototype
Working with JSON
Bitwise Operators
Run secondary tasks in the back ground AFTER the page has loaded.

When timer is done, job is added to the UI Queue.
Timers
Use += over function based concatenation

Use regexes to parse and slice
String Manipulation
Accessing data from a literal and a local variable are always fastest

Property Depth matters!
name.name.name

Object and arrays data referenced 2+ times should be cached locally
Data Access
Literal values
(strings, bools, numbers, null, undefined)
Variables
Object properties
Array items
Types of Data Access
An Even Better
Alternative…
Which is more efficient?
As conditions increase, switch becomes more and more optimal
Switch vs. If-Then-Else
YES! Combine the terminal condition evaluation and incrementing / decrementing…
More efficient looping
Can it be improved more?
More efficient looping
Can this loop be improved?
More efficient looping
What matters?
Amount of work being performed
Number of iterations

Do Less Work!!
Avoid lookups inside loop
Reduce number of calculation being performed
Efficient Looping
for
for-in
for-each
array.forEach()
do-while
while
Loops
Data vs. Attributes
Use the
Data Object instead!
What’s wrong with this?
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
stopPropagation(), preventDefaults(), etc.
Event Delegation
Much faster than using JavaScript and DOM to iterate and narrow down a list of elements
Supported in IE8+
querySelectorAll()
Always use the most optimum methods for crawling the DOM
Traversing
Avoid Reflow
Avoid Reflow
Repaint and Reflow
DOM Tree
Representation of the page structure
Render Tree
Representation of how the DOM nodes will be displayed
At least one node for every node in the DOM tree (excludes hidden nodes)
DOM Tree
vs.
Render Tree
DOM
Under The Hood
Optimize use of
HTMLCollections
Optimize use of
HTMLCollections
Lets improve
this method…
Examples:
document.getElementsByTagName
document.getElemenetsByClassName
document.images
document.forms

They looks like an array but they are not!
HTMLCollections
What is the outcome
of this method?
DOM and the
JavaScript Engine

DOM
Lazy Loading
How can this method
be improved?
Prototypes
Local variables missing the var keyword are automatically instantiated in the global namespace!
Never forget your ‘var’
What’s missing?
Pros:
Access to variables outside the function
Cons:
Adds to the scope chain
Requires a new execution context
Closures
(anonymous functions)
Both add to the scope chain!
With and Try-Catch
Cache any out-of-scope variables referenced more than once

(Especially global variables!)
Managing Scope
Scope Chain
The right optimization strategy will differ by application

Do what makes sense

Pick your battles

Consider maintainability

Challenge your assumptions regularly
Approaching
Optimization
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
Objectives
All selectors are NOT created equal

Think about what is going on under the covers…

Consider the following selectors…
Selecting the
Right Selector
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…
Remember…
Consider
Combined Approach
YES! Combine control condition and
control variable into a single statement….
More efficient looping
Avoid Function based loops (including Array.foreach())
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
Deciding which
loop to use
The DOM is not a database!
Traversing the DOM to retrieve data stored in attributes is extremely inefficient.

Data Property
Does not have to read and write to the DOM
Only has to be written one time
Accommodates arrays and complex objects
Further optimized by built-in caching
Data vs. Attributes
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
DocumentFragment
Reduce the number of reflows

Group styles
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 when you must
Avoid Reflow
Condenses the global namespace

Reduces search time for its descendants

Set distant namespaces to a variable to reduce search!
Namespacing
Improving JavaScript Performance
John Lawrimore
Pros:
Simplifies code
Cons:
Slow
Prototypes tend to live far away from the context where they are used.
Presenter
YSlow
Reading Material
Senior Consultant at Improving Enterprises
Microsoft enthusiast
Background heavy in web applications development
Was unable to come up with interesting fact about self
(except I use an Apple computer, phone, tablet, and I hate IE)
John Lawrimore
john.lawrimore@improvingenterprises.com
AMD
AMD
require.js
= Asynchronous Module Definition
Grade your site's optimizations
High Performance JavaScript
Nicholas C. Zakas
Web Workers
UI Thread
Responsibilities: *
Draw UI
Execute JavaScript
* Can only do ONE at a time!
(Work to be done must wait in the UI Queue)
New option for asynchronous execution in HTML5

Operates outside of UI Thread

Trigger specified event handlers when completed.

NEVER use With and use Try-Catch sparingly
Access this Presentation Later
http://johnlawrimore.com/jsperformance
Full transcript