SlideShare a Scribd company logo
Writing Efficient JavaScript
  What makes JavaScript slow and what to do about it




Nicholas C. Zakas
Principal Front End Engineer, Yahoo!
Velocity – June 2009
Who's this guy?
• Principal Front End Engineer, Yahoo! Homepage
• YUI Contributor
• Author
Writing Efficient JavaScript
Why slow?
We grew up
Browsers didn't
In the Beginning
Now
What's the
problem?
No compilation!*

* Humor me for now. It'll make this easier.
Writing Efficient JavaScript
Browsers
won't
help
your
code!!!!
Didn't Matter Then
Didn't Matter Then
• JavaScript used for simple form validation or
  image hovers
• Slow Internet connections
   – People expected to wait
• Click-and-go model
• Each page contained very little code
Matters Now
Matters Now
• Ajax and Web 2.0
• More JavaScript code than ever before
• Fast Internet connections
   – People have come to expect speed
• Applications that stay open for a long time
   – Gmail
   – Facebook
• Download and execute more code as you interact
Who will help
 your code?
Writing Efficient JavaScript
Disclaimer
What follows are graphic depictions of the parts of JavaScript that
are slow. Where appropriate, the names of the offenders have been
changed to protect their identities. All of the data, unless otherwise
noted, is for the browsers that are being used by the majority of web
users right now, in 2009. The techniques presented herein will
remain valid at least for the next 2-3 years. None of the techniques
will have to be reversed once browsers with super powers are the
norm and handle all optimizations for us. You should not take the
techniques addressed in this presentation as things you should do all
of the time. Measure your performance first, find the bottlenecks,
then apply the appropriate techniques to help your specific
bottlenecks. Premature optimization is fruitless and should be
avoided at all costs.
JavaScript Performance Issues
•   Scope management
•   Data access
•   Loops
•   DOM
•   Browser limits
Writing Efficient JavaScript
Scope Chains
When a Function Executes
• An execution context is created
• The context's scope chain is initialized with the
  members of the function's [[Scope]] collection
• An activation object is created containing all local
  variables
• The activation object is pushed to the front of the
  context's scope chain
Execution Context




Identifier Resolution
• Start at scope chain position 0
• If not found go to position 1
• Rinse, repeat
Identifier Resolution
• Local variables = fast!
• The further into the chain, the slower the
  resolution
Identifier Resolution (Reads)
                              200


                              180


                              160


                              140
                                                                                     Firefox 3
Time (ms) per 200,000 reads




                                                                                     Firefox 3.5 Beta 4
                              120                                                    Chrome 1
                                                                                     Chrome 2
                                                                                     Internet Explorer 7
                              100
                                                                                     Internet Explorer 8
                                                                                     Opera 9.64
                              80                                                     Opera 10 Beta
                                                                                     Safari 3.2
                                                                                     Safari 4
                              60


                              40


                              20


                               0
                                    1   2         3                      4   5   6
                                                      Identifier Depth
Identifer Resolution (Writes)
                               200


                               180


                               160


                               140
                                                                                      Firefox 3
Time (ms) per 200,000 writes




                                                                                      Firefox 3.5 Beta 4
                               120                                                    Chrome 1
                                                                                      Chrome 2
                                                                                      Internet Explorer 7
                               100
                                                                                      Internet Explorer 8
                                                                                      Opera 9.64
                               80                                                     Opera 10 Beta
                                                                                      Safari 3.2
                                                                                      Safari 4
                               60


                               40


                               20


                                0
                                     1   2         3                      4   5   6
                                                       Identifier Depth
Scope Chain Augmentation
• The with statement
• The catch clause of try-catch
• Both add an object to the front of the scope chain
Inside of Global Function
Inside of with/catch Statement




• Local variables now in second slot
• with/catch variables now in first slot
“with statement
considered harmful”
-Douglas Crockford
Closures
• The [[Scope]] property of closures begins with at
  least two objects
• Calling the closure means three objects in the
  scope chain (minimum)
Writing Efficient JavaScript
Closures
Inside of Closure
Recommendations
• Store out-of-scope variables in local variables
   – Especially global variables
• Avoid the with statement
   – Adds another object to the scope chain, so local
     function variables are now one step away
   – Use local variables instead
• Be careful with try-catch
   – The catch clause also augments the scope chain
• Use closures sparingly
• Don't forget var when declaring variables
Writing Efficient JavaScript
JavaScript Performance Issues
•   Scope management
•   Data access
•   Loops
•   DOM
•   Browser limits
Places to Access Data
•   Literal value
•   Variable
•   Object property
•   Array item
Data Access Performance
• Accessing data from a literal or a local variable is
  fastest
   – The difference between literal and local variable is
     negligible in most cases
• Accessing data from an object property or array
  item is more expensive
   – Which is more expensive depends on the browser
Data Access
                              100


                              90


                              80


                              70
Time (ms) per 200,000 reads




                              60
                                                                                                                                                              Literal
                                                                                                                                                              Local Variable
                              50
                                                                                                                                                              Array Item
                                                                                                                                                              Object Property
                              40


                              30


                              20


                              10


                               0
                                    Firefox 3   Firefox 3.5   Chrome 1   Chrome 2    Internet     Internet    Opera 9.64   Opera 10   Safari 3.2   Safari 4
                                                  Beta 4                            Explorer 7   Explorer 8                 Beta
Property Depth
• object.name < object.name.name
• The deeper the property, the longer it takes to
  retrieve
Property Depth (Reads)
                              250




                              200


                                                                     Firefox 3
Time (ms) per 200,000 reads




                                                                     Firefox 3.5 Beta 4
                              150                                    Chrome 1
                                                                     Chrome 2
                                                                     Internet Explorer 7
                                                                     Internet Explorer 8
                                                                     Opera 9.64
                              100                                    Opera 10 Beta
                                                                     Safari 3.2
                                                                     Safari 4


                              50




                               0
                                    1   2                    3   4
                                            Property Depth
Property Notation
• Difference between object.name and
  object[“name”]?
  – Generally no
  – Exception: Dot notation is faster in Safari
Recommendations
• Store these in a local variable:
   – Any object property accessed more than once
   – Any array item accessed more than once
• Minimize deep object property/array item lookup
Writing Efficient JavaScript
-5%   -10%   -33%
JavaScript Performance Issues
•   Scope management
•   Data Access
•   Loops
•   DOM
•   Browser limits
Loops
• ECMA-262, 3rd Edition:
  –   for
  –   for-in
  –   do-while
  –   while
• ECMA-357, 2nd Edition:
  – for each
Writing Efficient JavaScript
Which loop?
It doesn't matter!
What Does Matter?
• Amount of work done per iteration
   – Includes terminal condition evaluation and
     incrementing/decrementing
• Number of iterations
• These don't vary by loop type
Fixing Loops
• Decrease amount of work per iteration
• Decrease number of iterations
Writing Efficient JavaScript
Writing Efficient JavaScript
Writing Efficient JavaScript
Easy Fixes
• Eliminate object property/array item lookups
Writing Efficient JavaScript
Easy Fixes
• Eliminate object property/array item lookups
• Combine control condition and control variable
  change
   – Work avoidance!
Two evaluations:
j < len
j < len == true
One evaluation
j-- == true




                 -50%
Easy Fixes
• Eliminate object property/array item lookups
• Combine control condition and control variable
  change
   – Work avoidance!
Things to Avoid for Speed
• ECMA-262, 3rd Edition:
   – for-in
               nd
• ECMA-357, 2 Edition:
   – for each
• ECMA-262, 5th Edition:
   – array.forEach()
• Function-based iteration:
   –   jQuery.each()
   –   Y.each()
   –   $each
   –   Enumerable.each()
• Introduces additional function
• Function requires execution (execution context
  created, destroyed)
• Function also creates additional object in scope
  chain

                                              8x
JavaScript Performance Issues
•   Scope management
•   Data Access
•   Loops
•   DOM
•   Browser limits
DOM
HTMLCollection
HTMLCollection Objects
• document.images, document.forms,
  etc.
• getElementsByTagName()
• getElementsByClassName()
Note: Collections in the HTML DOM are assumed to be live
meaning that they are automatically updated when the underlying
                      document is changed.
Infinite Loop!
HTMLCollection Objects
• Look like arrays, but aren't
   – Bracket notation
   – length property
• Represent the results of a specific query
• The query is re-run each time the object is
  accessed
   – Include accessing length and specific items
   – Much slower than accessing the same on arrays
   – Exceptions: Opera, Safari
15x   53x   68x
=   =   =
HTMLCollection Objects
• Minimize property access
   – Store length, items in local variables if used frequently
• If you need to access items in order frequently,
  copy into a regular array
function array(items){
    try {
        return Array.prototype.slice.call(items);
    } catch (ex){
        var i      = 0,
            len    = items.length,
            result = Array(len);

        while (i < len){
            result[i] = items[i];
            i++;
        }
    }

    return result;
}
Repaint & Reflow
Repaint...is what happens
whenever something is made
visible when it was not
previously visible, or vice
versa, without altering the
layout of the document.
  - Mark 'Tarquin' Wilton-Jones, Opera
When Repaint?
• Change to visibility
• Formatting styles changed
  –   Backgrounds
  –   Borders
  –   Colors
  –   Anything that doesn't change the size, shape, or
      position of the element but does change its
      appearance
• When a reflow occurs
Reflow is the process by
which the geometry of the
layout engine's formatting
objects are computed.
           - Chris Waterson, Mozilla
When Reflow?
•   Initial page load
•   Browser window resize
•   DOM nodes added or removed
•   Layout styles applied
•   Layout information retrieved
Addressing Repaint & Reflow
• Perform DOM changes off-document
• Groups style changes
• Cache retrieved layout information
Reflow!
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
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
No
      reflow!


Reflow!
Addressing Repaint & Reflow
• Perform DOM changes off-document
• Group style changes
• Cache retrieved layout information
Repaint!      Reflow!


                        Reflow!




           Repaint!
What to do?
• Minimize changes on style property
• Define CSS class with all changes and just
  change className property
• Set cssText on the element directly
Reflow!
Reflow!
Addressing Repaint & Reflow
• Perform DOM changes off-document
• Group style changes
• Cache retrieved layout information
  – Reflow may be cached
Reflow?
              Reflow?




    Reflow?
What to do?
• Minimize access to layout information
• If a value is used more than once, store in local
  variable
Speed Up Your DOM
•   Be careful using HTMLCollection objects
•   Perform DOM manipulations off the document
•   Group CSS changes to minimize repaint/reflow
•   Be careful when accessing layout information
JavaScript Performance Issues
•   Scope management
•   Data Access
•   Loops
•   DOM
•   Browser limits
Call Stack   Runaway Timer
Call Stack
• Controls how many functions can be executed in
  a single process
• Varies depending on browser and JavaScript
  engine
• Errors occur when call stack size is exceeded
Note: Internet Explorer changes call stack size based on available memory
Call Stack Overflow
• Error messages
  –   IE: “Stack overflow at line x”
  –   Firefox: “Too much recursion”
  –   Safari: “Maximum call stack size exceeded.”
  –   Opera: “Abort (control stack overflow)”
  –   Chrome: n/a
• Browsers throw a regular JavaScript error when
  this occurs
  – Exception: Opera just aborts the script
Runaway Script Timer
• Designed to prevent the browser from affecting
  the operating system
• Limits the amount of time a script is allowed to
  execute
• Two types of limits:
   – Execution time
   – Number of statements
• Always pops up a scary dialog to the user
• Exception: Opera has no runaway timer
Internet Explorer
Firefox
Safari
Chrome
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
The Browser UI Thread
• Shared between JavaScript and UI updates
• Only one can happen at a time
• Page UI frozen while JavaScript is executing
• A queue of actions is kept containing what to do next
Browser Limit Causes
• Too much DOM interaction
  – Repaint & reflow
• Too much recursion
• Long-running loops
Writing Efficient JavaScript
Recursion Pattern #1
Recursion Pattern #2
Recursion Solutions
• Iteration
Writing Efficient JavaScript
Writing Efficient JavaScript
Recursion Solutions
• Iteration
• Memoization
Writing Efficient JavaScript
Writing Efficient JavaScript
Writing Efficient JavaScript
Browser Limit Causes
• Too much DOM interaction
  – Repaint & reflow
• Too much recursion
• Long-running loops
  – Too much per iteration
  – Too many iterations
  – Lock up the browser UI
setTimeout()
• Schedules a task to be added to the UI queue later
• Can be used to yield the UI thread
• Timer functions begin with a new call stack
• Extremely useful for avoiding browser limits
Loops
galore!
Just do
      one pass




 Defer
the rest
Writing Efficient JavaScript
Avoiding Browser Limits
• Mind your DOM
  – Limit repaint/reflow
• Mind your recursion
  – Consider iteration or memoization
• Mind your loops
  – Keep small, sprinkle setTimeout() liberally if needed
Will it be like this forever?
No
Browsers With Optimizing Engines
•   Chrome (V8)
•   Safari 4+ (Nitro)
•   Firefox 3.5+ (TraceMonkey)
•   Opera 10? 11? (Carakan)

All use native code generation and JIT compiling to
        achieve faster JavaScript execution.
Summary
Writing Efficient JavaScript
Writing Efficient JavaScript
Writing Efficient JavaScript
Writing Efficient JavaScript
Writing Efficient JavaScript
Writing Efficient JavaScript
Writing Efficient JavaScript
Writing Efficient JavaScript
Questions?
Etcetera
• My blog:    www.nczonline.net
• My email:   nzakas@yahoo-inc.com
• Twitter:    @slicknet
Creative Commons Images Used
•   http://www.flickr.com/photos/neogabox/3367815587/
•   http://www.flickr.com/photos/lydz/3355198458/
•   http://www.flickr.com/photos/37287477@N00/515178157/
•   http://www.flickr.com/photos/ottoman42/455242/
•   http://www.flickr.com/photos/hippie/2406411610/
•   http://www.flickr.com/photos/flightsaber/2204113449/
•   http://www.flickr.com/photos/crumbs/2702429363/
•   http://www.flickr.com/photos/oberazzi/318947873/
•   http://www.flickr.com/photos/vox_efx/2912195591/
•   http://www.flickr.com/photos/fornal/385054886/
•   http://www.flickr.com/photos/29505605@N08/3198765320/
•   http://www.flickr.com/photos/torley/2361164281/
•   http://www.flickr.com/photos/rwp-roger/171490824/

More Related Content

What's hot (20)

PDF
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
J V
 
PPTX
Attacking thru HTTP Host header
Sergey Belov
 
PDF
Cross-domain requests with CORS
Vladimir Dzhuvinov
 
PDF
Entity provider selection confusion attacks in JAX-RS applications
Mikhail Egorov
 
PPTX
Owasp zap
penetration Tester
 
PPTX
Getting up to speed with MirrorMaker 2 | Mickael Maison, IBM and Ryanne Dolan...
HostedbyConfluent
 
PPTX
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Soroush Dalili
 
PDF
From Zero to Hero with Kafka Connect
confluent
 
PDF
Windows logging cheat sheet
Michael Gough
 
PPTX
API Management in Azure
Tomasso Groenendijk
 
PDF
Offzone | Another waf bypass
Дмитрий Бумов
 
PPTX
Waf bypassing Techniques
Avinash Thapa
 
PDF
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
Frans Rosén
 
PPTX
Cross site scripting
kinish kumar
 
PDF
Would you Rather Have Telemetry into 2 Attacks or 20? An Insight Into Highly ...
MITRE ATT&CK
 
PDF
Owasp top 10
YasserElsnbary
 
PDF
Broken access controls
Akansha Kesharwani
 
PDF
A little bit about code injection in WebApplication Frameworks (CVE-2018-1466...
ufpb
 
PPTX
Apache Kafka vs RabbitMQ: Fit For Purpose / Decision Tree
Slim Baltagi
 
PDF
Expressjs
Yauheni Nikanovich
 
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
J V
 
Attacking thru HTTP Host header
Sergey Belov
 
Cross-domain requests with CORS
Vladimir Dzhuvinov
 
Entity provider selection confusion attacks in JAX-RS applications
Mikhail Egorov
 
Getting up to speed with MirrorMaker 2 | Mickael Maison, IBM and Ryanne Dolan...
HostedbyConfluent
 
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Soroush Dalili
 
From Zero to Hero with Kafka Connect
confluent
 
Windows logging cheat sheet
Michael Gough
 
API Management in Azure
Tomasso Groenendijk
 
Offzone | Another waf bypass
Дмитрий Бумов
 
Waf bypassing Techniques
Avinash Thapa
 
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
Frans Rosén
 
Cross site scripting
kinish kumar
 
Would you Rather Have Telemetry into 2 Attacks or 20? An Insight Into Highly ...
MITRE ATT&CK
 
Owasp top 10
YasserElsnbary
 
Broken access controls
Akansha Kesharwani
 
A little bit about code injection in WebApplication Frameworks (CVE-2018-1466...
ufpb
 
Apache Kafka vs RabbitMQ: Fit For Purpose / Decision Tree
Slim Baltagi
 

Viewers also liked (20)

PDF
Javascript Best Practices
Christian Heilmann
 
PPTX
Maintainable JavaScript 2012
Nicholas Zakas
 
PDF
Scalable JavaScript Application Architecture
Nicholas Zakas
 
PDF
JavaScript Programming
Sehwan Noh
 
PDF
Unobtrusive JavaScript with jQuery
Simon Willison
 
PDF
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Nicholas Zakas
 
PDF
JavaScript Library Overview
jeresig
 
PPTX
Javascript
Sun Technlogies
 
PDF
HTML5 JavaScript APIs
Remy Sharp
 
PPTX
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas
 
PPTX
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
PDF
Speed Up Your JavaScript
Nicholas Zakas
 
PPT
Satellite communications ppt
Niranjan kumar
 
PPT
Work with my sql database in java
Asya Dudnik
 
PDF
Computer Vision
Inman News
 
PDF
High Performance JavaScript - Fronteers 2010
Nicholas Zakas
 
PDF
High Performance JavaScript (YUIConf 2010)
Nicholas Zakas
 
PDF
JavaScript in the Real World
Andrew Nesbitt
 
PPTX
An overview of java script in 2015 (ecma script 6)
LearningTech
 
PPTX
Aspnet mvc4
LearningTech
 
Javascript Best Practices
Christian Heilmann
 
Maintainable JavaScript 2012
Nicholas Zakas
 
Scalable JavaScript Application Architecture
Nicholas Zakas
 
JavaScript Programming
Sehwan Noh
 
Unobtrusive JavaScript with jQuery
Simon Willison
 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Nicholas Zakas
 
JavaScript Library Overview
jeresig
 
Javascript
Sun Technlogies
 
HTML5 JavaScript APIs
Remy Sharp
 
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas
 
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
Speed Up Your JavaScript
Nicholas Zakas
 
Satellite communications ppt
Niranjan kumar
 
Work with my sql database in java
Asya Dudnik
 
Computer Vision
Inman News
 
High Performance JavaScript - Fronteers 2010
Nicholas Zakas
 
High Performance JavaScript (YUIConf 2010)
Nicholas Zakas
 
JavaScript in the Real World
Andrew Nesbitt
 
An overview of java script in 2015 (ecma script 6)
LearningTech
 
Aspnet mvc4
LearningTech
 
Ad

Similar to Writing Efficient JavaScript (20)

PDF
JavaScript Variable Performance
Nicholas Zakas
 
KEY
HTML5 를 이용한 하이브리드앱 제작
Zany Lee
 
PDF
Performance Of Web Applications On Client Machines
Curelet Marius
 
PDF
Firefox3.5 And Next
Channy Yun
 
KEY
HTML5 웹 표준과 모바일 개발
Zany Lee
 
PDF
TWaver Flex Performance Report
253725291
 
DOCX
หน่วยการเรียนรู้ที่ 4
Papichaya Chengtong
 
PPTX
WebKit vs. the mobile Web
Josh Tumath
 
PDF
Seatwave Web Peformance Optimisation Case Study
Stephen Thair
 
PPTX
Microsoft Web Platform and Internet Explorer 8 for PHP developers
Glen Gordon
 
PDF
Tablet browser-OS comparison
Principled Technologies
 
PDF
69-kauri
tutorialsruby
 
PDF
69-kauri
tutorialsruby
 
PDF
69-kauri
tutorialsruby
 
PDF
69-kauri
tutorialsruby
 
PDF
Mozilla in Vietnam 2009
Gen Kanai
 
PDF
MeasureWorks - Emerce Conversion Event 20 April
MeasureWorks
 
KEY
Building Faster Websites
Matthew Farina
 
PPTX
Complexity At The Edge How To Maximize The Mobile Opportunity
Compuware APM
 
PDF
[E4]triple s deview
NAVER D2
 
JavaScript Variable Performance
Nicholas Zakas
 
HTML5 를 이용한 하이브리드앱 제작
Zany Lee
 
Performance Of Web Applications On Client Machines
Curelet Marius
 
Firefox3.5 And Next
Channy Yun
 
HTML5 웹 표준과 모바일 개발
Zany Lee
 
TWaver Flex Performance Report
253725291
 
หน่วยการเรียนรู้ที่ 4
Papichaya Chengtong
 
WebKit vs. the mobile Web
Josh Tumath
 
Seatwave Web Peformance Optimisation Case Study
Stephen Thair
 
Microsoft Web Platform and Internet Explorer 8 for PHP developers
Glen Gordon
 
Tablet browser-OS comparison
Principled Technologies
 
69-kauri
tutorialsruby
 
69-kauri
tutorialsruby
 
69-kauri
tutorialsruby
 
69-kauri
tutorialsruby
 
Mozilla in Vietnam 2009
Gen Kanai
 
MeasureWorks - Emerce Conversion Event 20 April
MeasureWorks
 
Building Faster Websites
Matthew Farina
 
Complexity At The Edge How To Maximize The Mobile Opportunity
Compuware APM
 
[E4]triple s deview
NAVER D2
 
Ad

More from Nicholas Zakas (20)

PPTX
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas
 
PPTX
Enough with the JavaScript already!
Nicholas Zakas
 
PPTX
The Pointerless Web
Nicholas Zakas
 
PPTX
JavaScript Timers, Power Consumption, and Performance
Nicholas Zakas
 
PPTX
Scalable JavaScript Application Architecture 2012
Nicholas Zakas
 
PDF
Maintainable JavaScript 2011
Nicholas Zakas
 
PDF
High Performance JavaScript 2011
Nicholas Zakas
 
PDF
Mobile Web Speed Bumps
Nicholas Zakas
 
PDF
High Performance JavaScript (Amazon DevCon 2011)
Nicholas Zakas
 
PDF
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas
 
PDF
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas
 
PDF
YUI Test The Next Generation (YUIConf 2010)
Nicholas Zakas
 
PDF
Nicholas' Performance Talk at Google
Nicholas Zakas
 
PDF
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas
 
PDF
Performance on the Yahoo! Homepage
Nicholas Zakas
 
PDF
High Performance JavaScript - jQuery Conference SF Bay Area 2010
Nicholas Zakas
 
PPT
Responsive interfaces
Nicholas Zakas
 
PDF
Extreme JavaScript Compression With YUI Compressor
Nicholas Zakas
 
ODP
The New Yahoo! Homepage and YUI 3
Nicholas Zakas
 
PDF
Test Driven Development With YUI Test (Ajax Experience 2008)
Nicholas Zakas
 
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas
 
Enough with the JavaScript already!
Nicholas Zakas
 
The Pointerless Web
Nicholas Zakas
 
JavaScript Timers, Power Consumption, and Performance
Nicholas Zakas
 
Scalable JavaScript Application Architecture 2012
Nicholas Zakas
 
Maintainable JavaScript 2011
Nicholas Zakas
 
High Performance JavaScript 2011
Nicholas Zakas
 
Mobile Web Speed Bumps
Nicholas Zakas
 
High Performance JavaScript (Amazon DevCon 2011)
Nicholas Zakas
 
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas
 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas
 
YUI Test The Next Generation (YUIConf 2010)
Nicholas Zakas
 
Nicholas' Performance Talk at Google
Nicholas Zakas
 
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas
 
Performance on the Yahoo! Homepage
Nicholas Zakas
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
Nicholas Zakas
 
Responsive interfaces
Nicholas Zakas
 
Extreme JavaScript Compression With YUI Compressor
Nicholas Zakas
 
The New Yahoo! Homepage and YUI 3
Nicholas Zakas
 
Test Driven Development With YUI Test (Ajax Experience 2008)
Nicholas Zakas
 

Recently uploaded (20)

PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PDF
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PPTX
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
Practical Applications of AI in Local Government
OnBoard
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 

Writing Efficient JavaScript

  • 1. Writing Efficient JavaScript What makes JavaScript slow and what to do about it Nicholas C. Zakas Principal Front End Engineer, Yahoo! Velocity – June 2009
  • 2. Who's this guy? • Principal Front End Engineer, Yahoo! Homepage • YUI Contributor • Author
  • 8. Now
  • 10. No compilation!* * Humor me for now. It'll make this easier.
  • 14. Didn't Matter Then • JavaScript used for simple form validation or image hovers • Slow Internet connections – People expected to wait • Click-and-go model • Each page contained very little code
  • 16. Matters Now • Ajax and Web 2.0 • More JavaScript code than ever before • Fast Internet connections – People have come to expect speed • Applications that stay open for a long time – Gmail – Facebook • Download and execute more code as you interact
  • 17. Who will help your code?
  • 19. Disclaimer What follows are graphic depictions of the parts of JavaScript that are slow. Where appropriate, the names of the offenders have been changed to protect their identities. All of the data, unless otherwise noted, is for the browsers that are being used by the majority of web users right now, in 2009. The techniques presented herein will remain valid at least for the next 2-3 years. None of the techniques will have to be reversed once browsers with super powers are the norm and handle all optimizations for us. You should not take the techniques addressed in this presentation as things you should do all of the time. Measure your performance first, find the bottlenecks, then apply the appropriate techniques to help your specific bottlenecks. Premature optimization is fruitless and should be avoided at all costs.
  • 20. JavaScript Performance Issues • Scope management • Data access • Loops • DOM • Browser limits
  • 23. When a Function Executes • An execution context is created • The context's scope chain is initialized with the members of the function's [[Scope]] collection • An activation object is created containing all local variables • The activation object is pushed to the front of the context's scope chain
  • 24. Execution Context Identifier Resolution • Start at scope chain position 0 • If not found go to position 1 • Rinse, repeat
  • 25. Identifier Resolution • Local variables = fast! • The further into the chain, the slower the resolution
  • 26. Identifier Resolution (Reads) 200 180 160 140 Firefox 3 Time (ms) per 200,000 reads Firefox 3.5 Beta 4 120 Chrome 1 Chrome 2 Internet Explorer 7 100 Internet Explorer 8 Opera 9.64 80 Opera 10 Beta Safari 3.2 Safari 4 60 40 20 0 1 2 3 4 5 6 Identifier Depth
  • 27. Identifer Resolution (Writes) 200 180 160 140 Firefox 3 Time (ms) per 200,000 writes Firefox 3.5 Beta 4 120 Chrome 1 Chrome 2 Internet Explorer 7 100 Internet Explorer 8 Opera 9.64 80 Opera 10 Beta Safari 3.2 Safari 4 60 40 20 0 1 2 3 4 5 6 Identifier Depth
  • 28. Scope Chain Augmentation • The with statement • The catch clause of try-catch • Both add an object to the front of the scope chain
  • 29. Inside of Global Function
  • 30. Inside of with/catch Statement • Local variables now in second slot • with/catch variables now in first slot
  • 32. Closures • The [[Scope]] property of closures begins with at least two objects • Calling the closure means three objects in the scope chain (minimum)
  • 36. Recommendations • Store out-of-scope variables in local variables – Especially global variables • Avoid the with statement – Adds another object to the scope chain, so local function variables are now one step away – Use local variables instead • Be careful with try-catch – The catch clause also augments the scope chain • Use closures sparingly • Don't forget var when declaring variables
  • 38. JavaScript Performance Issues • Scope management • Data access • Loops • DOM • Browser limits
  • 39. Places to Access Data • Literal value • Variable • Object property • Array item
  • 40. Data Access Performance • Accessing data from a literal or a local variable is fastest – The difference between literal and local variable is negligible in most cases • Accessing data from an object property or array item is more expensive – Which is more expensive depends on the browser
  • 41. Data Access 100 90 80 70 Time (ms) per 200,000 reads 60 Literal Local Variable 50 Array Item Object Property 40 30 20 10 0 Firefox 3 Firefox 3.5 Chrome 1 Chrome 2 Internet Internet Opera 9.64 Opera 10 Safari 3.2 Safari 4 Beta 4 Explorer 7 Explorer 8 Beta
  • 42. Property Depth • object.name < object.name.name • The deeper the property, the longer it takes to retrieve
  • 43. Property Depth (Reads) 250 200 Firefox 3 Time (ms) per 200,000 reads Firefox 3.5 Beta 4 150 Chrome 1 Chrome 2 Internet Explorer 7 Internet Explorer 8 Opera 9.64 100 Opera 10 Beta Safari 3.2 Safari 4 50 0 1 2 3 4 Property Depth
  • 44. Property Notation • Difference between object.name and object[“name”]? – Generally no – Exception: Dot notation is faster in Safari
  • 45. Recommendations • Store these in a local variable: – Any object property accessed more than once – Any array item accessed more than once • Minimize deep object property/array item lookup
  • 47. -5% -10% -33%
  • 48. JavaScript Performance Issues • Scope management • Data Access • Loops • DOM • Browser limits
  • 49. Loops • ECMA-262, 3rd Edition: – for – for-in – do-while – while • ECMA-357, 2nd Edition: – for each
  • 53. What Does Matter? • Amount of work done per iteration – Includes terminal condition evaluation and incrementing/decrementing • Number of iterations • These don't vary by loop type
  • 54. Fixing Loops • Decrease amount of work per iteration • Decrease number of iterations
  • 58. Easy Fixes • Eliminate object property/array item lookups
  • 60. Easy Fixes • Eliminate object property/array item lookups • Combine control condition and control variable change – Work avoidance!
  • 61. Two evaluations: j < len j < len == true
  • 63. Easy Fixes • Eliminate object property/array item lookups • Combine control condition and control variable change – Work avoidance!
  • 64. Things to Avoid for Speed • ECMA-262, 3rd Edition: – for-in nd • ECMA-357, 2 Edition: – for each • ECMA-262, 5th Edition: – array.forEach() • Function-based iteration: – jQuery.each() – Y.each() – $each – Enumerable.each()
  • 65. • Introduces additional function • Function requires execution (execution context created, destroyed) • Function also creates additional object in scope chain 8x
  • 66. JavaScript Performance Issues • Scope management • Data Access • Loops • DOM • Browser limits
  • 67. DOM
  • 69. HTMLCollection Objects • document.images, document.forms, etc. • getElementsByTagName() • getElementsByClassName()
  • 70. Note: Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed.
  • 72. HTMLCollection Objects • Look like arrays, but aren't – Bracket notation – length property • Represent the results of a specific query • The query is re-run each time the object is accessed – Include accessing length and specific items – Much slower than accessing the same on arrays – Exceptions: Opera, Safari
  • 73. 15x 53x 68x
  • 74. = = =
  • 75. HTMLCollection Objects • Minimize property access – Store length, items in local variables if used frequently • If you need to access items in order frequently, copy into a regular array
  • 76. function array(items){ try { return Array.prototype.slice.call(items); } catch (ex){ var i = 0, len = items.length, result = Array(len); while (i < len){ result[i] = items[i]; i++; } } return result; }
  • 78. Repaint...is what happens whenever something is made visible when it was not previously visible, or vice versa, without altering the layout of the document. - Mark 'Tarquin' Wilton-Jones, Opera
  • 79. When Repaint? • Change to visibility • Formatting styles changed – Backgrounds – Borders – Colors – Anything that doesn't change the size, shape, or position of the element but does change its appearance • When a reflow occurs
  • 80. Reflow is the process by which the geometry of the layout engine's formatting objects are computed. - Chris Waterson, Mozilla
  • 81. When Reflow? • Initial page load • Browser window resize • DOM nodes added or removed • Layout styles applied • Layout information retrieved
  • 82. Addressing Repaint & Reflow • Perform DOM changes off-document • Groups style changes • Cache retrieved layout information
  • 84. 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
  • 85. 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
  • 86. No reflow! Reflow!
  • 87. Addressing Repaint & Reflow • Perform DOM changes off-document • Group style changes • Cache retrieved layout information
  • 88. Repaint! Reflow! Reflow! Repaint!
  • 89. What to do? • Minimize changes on style property • Define CSS class with all changes and just change className property • Set cssText on the element directly
  • 92. Addressing Repaint & Reflow • Perform DOM changes off-document • Group style changes • Cache retrieved layout information – Reflow may be cached
  • 93. Reflow? Reflow? Reflow?
  • 94. What to do? • Minimize access to layout information • If a value is used more than once, store in local variable
  • 95. Speed Up Your DOM • Be careful using HTMLCollection objects • Perform DOM manipulations off the document • Group CSS changes to minimize repaint/reflow • Be careful when accessing layout information
  • 96. JavaScript Performance Issues • Scope management • Data Access • Loops • DOM • Browser limits
  • 97. Call Stack Runaway Timer
  • 98. Call Stack • Controls how many functions can be executed in a single process • Varies depending on browser and JavaScript engine • Errors occur when call stack size is exceeded
  • 99. Note: Internet Explorer changes call stack size based on available memory
  • 100. Call Stack Overflow • Error messages – IE: “Stack overflow at line x” – Firefox: “Too much recursion” – Safari: “Maximum call stack size exceeded.” – Opera: “Abort (control stack overflow)” – Chrome: n/a • Browsers throw a regular JavaScript error when this occurs – Exception: Opera just aborts the script
  • 101. Runaway Script Timer • Designed to prevent the browser from affecting the operating system • Limits the amount of time a script is allowed to execute • Two types of limits: – Execution time – Number of statements • Always pops up a scary dialog to the user • Exception: Opera has no runaway timer
  • 104. Safari
  • 105. Chrome
  • 106. 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
  • 107. The Browser UI Thread • Shared between JavaScript and UI updates • Only one can happen at a time • Page UI frozen while JavaScript is executing • A queue of actions is kept containing what to do next
  • 108. Browser Limit Causes • Too much DOM interaction – Repaint & reflow • Too much recursion • Long-running loops
  • 119. Browser Limit Causes • Too much DOM interaction – Repaint & reflow • Too much recursion • Long-running loops – Too much per iteration – Too many iterations – Lock up the browser UI
  • 120. setTimeout() • Schedules a task to be added to the UI queue later • Can be used to yield the UI thread • Timer functions begin with a new call stack • Extremely useful for avoiding browser limits
  • 122. Just do one pass Defer the rest
  • 124. Avoiding Browser Limits • Mind your DOM – Limit repaint/reflow • Mind your recursion – Consider iteration or memoization • Mind your loops – Keep small, sprinkle setTimeout() liberally if needed
  • 125. Will it be like this forever?
  • 126. No
  • 127. Browsers With Optimizing Engines • Chrome (V8) • Safari 4+ (Nitro) • Firefox 3.5+ (TraceMonkey) • Opera 10? 11? (Carakan) All use native code generation and JIT compiling to achieve faster JavaScript execution.
  • 138. Etcetera • My blog: www.nczonline.net • My email: [email protected] • Twitter: @slicknet
  • 139. Creative Commons Images Used • http://www.flickr.com/photos/neogabox/3367815587/ • http://www.flickr.com/photos/lydz/3355198458/ • http://www.flickr.com/photos/37287477@N00/515178157/ • http://www.flickr.com/photos/ottoman42/455242/ • http://www.flickr.com/photos/hippie/2406411610/ • http://www.flickr.com/photos/flightsaber/2204113449/ • http://www.flickr.com/photos/crumbs/2702429363/ • http://www.flickr.com/photos/oberazzi/318947873/ • http://www.flickr.com/photos/vox_efx/2912195591/ • http://www.flickr.com/photos/fornal/385054886/ • http://www.flickr.com/photos/29505605@N08/3198765320/ • http://www.flickr.com/photos/torley/2361164281/ • http://www.flickr.com/photos/rwp-roger/171490824/