SlideShare une entreprise Scribd logo
1  sur  90
Télécharger pour lire hors ligne
Speed Up Your JavaScript
          Nicholas C. Zakas
Principal Front End Engineer, Yahoo!
          x
   Web E ponents – June 4, 2009
Who's this guy?
• Principal Front End Engineer, Yahoo! Homepage
• YUI Contributor
• Author
Why slow?
Bad compilation?
No
No compilation!*

* Humor me for now. It'll make this easier.
Browsers
won't
help
your
code!!!!
Who will help
 your code?
JavaScript Performance Issues
•   Scope management
•   Data access
•   Loops
•   DOM
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.1 Beta 3
                              120                                                   Chrome 1
                                                                                    Chrome 2 Beta
                                                                                    Internet Explorer 7
                              100
                                                                                    Internet Explorer 8
                                                                                    Opera 9.64
                              80                                                    Opera 10 Alpha
                                                                                    Safari 3.2
                                                                                    Safari 4 Beta
                              60


                              40


                              20


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


                               180


                               160


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




                                                                                      Firefox 3.1 Beta 3
                               120                                                    Chrome 1
                                                                                      Chrome 2 Beta
                                                                                      Internet Explorer 7
                               100
                                                                                      Internet Explorer 8
                                                                                      Opera 9.64
                               80                                                     Opera 10 Alpha
                                                                                      Safari 3.2
                                                                                      Safari 4 Beta
                               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 variables now in first slot
“with statement
considered harmful”
-Douglas Crockford
Closures
• The [[Scope]] property of closures begins with two
  objects
• Calling the closure means three objects in the
  scope chain (minimum)
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
JavaScript Performance Issues
•   Scope management
•   Data access
•   Loops
•   DOM
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.1   Chrome 1   Chrome 2    Internet     Internet    Opera 9.64   Opera 10   Safari 3.2   Safari 4
                                                  Beta 3                   Beta     Explorer 7   Explorer 8                 Alpha                   Beta
Property Depth
• object.name < object.name.name
• The deeper the property, the longer it takes to
  retrieve
Property Depth
                              250




                              200




                                                                      Firefox 3
Time (ms) per 200,000 reads




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




                              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
-5%   -10%   -33%
JavaScript Performance Issues
•   Scope management
•   Data Access
•   Loops
•   DOM
Loops
• ECMA-262, 3rd Edition:
  –   for
  –   for-in
  –   do-while
  –   while
• ECMA-357, 2nd Edition:
  – for each
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
Easy Fixes
• Eliminate object property/array item lookups
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
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;
}
Reflow
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
Reflow!
DocumentFragment
• A document-like object
• Not visually represented
• Considered a child of the document from which it
  was created
• When passed to addChild(), appends all of
  its children rather than itself
No
      reflow!


Reflow!
When Reflow?
•   Initial page load
•   Browser window resize
•   DOM nodes added or removed
•   Layout styles applied
•   Layout information retrieved
Reflow!             Reflow!




          Reflow!
What to do?
• Minimize changes on style property
• Define CSS class with all changes and just
  change className property
Reflow!
When Reflow?
•   Initial page load
•   Browser window resize
•   DOM nodes added or removed
•   Layout styles applied
•   Layout information retrieved
    – Only if reflow is 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
•   Change CSS classes, not CSS styles
•   Be careful when accessing layout information
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.
Hang in there!
Summary
•   Mind your scope
•   Local variables are your friends
•   Function execution comes at a cost
•   Keep loops small
•   Avoid doing work whenever possible
•   Minimize DOM interaction
•   Use a good browser and encourage others to do
    the same
Questions?
Etcetera
• My blog:    www.nczonline.net
• My email:   nzakas@yahoo-inc.com
• Twitter:    @slicknet
Creative Commons Images Used
•   http://www.flickr.com/photos/blackbutterfly/3051019058/
•   http://www.flickr.com/photos/23816315@N07/2528296337/
•   http://www.flickr.com/photos/37287477@N00/515178157/
•   http://www.flickr.com/photos/ottoman42/455242/
•   http://www.flickr.com/photos/crumbs/2702429363/
•   http://flickr.com/photos/oberazzi/318947873/

Contenu connexe

Tendances

Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven Testing
Maveryx
 

Tendances (20)

MOPCON_2022.pdf
MOPCON_2022.pdfMOPCON_2022.pdf
MOPCON_2022.pdf
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Framework
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
Cypress, Playwright, Selenium, or WebdriverIO? Let the Engineers Speak!
Cypress, Playwright, Selenium, or WebdriverIO? Let the Engineers Speak!Cypress, Playwright, Selenium, or WebdriverIO? Let the Engineers Speak!
Cypress, Playwright, Selenium, or WebdriverIO? Let the Engineers Speak!
 
Webdriver io presentation
Webdriver io presentationWebdriver io presentation
Webdriver io presentation
 
웹 접근성 평가도구 OpenWAX 뜯어보기
웹 접근성 평가도구 OpenWAX 뜯어보기웹 접근성 평가도구 OpenWAX 뜯어보기
웹 접근성 평가도구 OpenWAX 뜯어보기
 
웹 Front-End 실무 이야기
웹 Front-End 실무 이야기웹 Front-End 실무 이야기
웹 Front-End 실무 이야기
 
Visual Studio 開發密技大補帖 | Study4.TW 2021 小聚#2
Visual Studio 開發密技大補帖 | Study4.TW 2021 小聚#2Visual Studio 開發密技大補帖 | Study4.TW 2021 小聚#2
Visual Studio 開發密技大補帖 | Study4.TW 2021 小聚#2
 
Keyword Driven Testing
Keyword Driven TestingKeyword Driven Testing
Keyword Driven Testing
 
Django
DjangoDjango
Django
 
Magento2.3 API Functional Testing
Magento2.3 API Functional TestingMagento2.3 API Functional Testing
Magento2.3 API Functional Testing
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
 
ATDD Using Robot Framework
ATDD Using Robot FrameworkATDD Using Robot Framework
ATDD Using Robot Framework
 
.Net Core
.Net Core.Net Core
.Net Core
 
신입 웹 개발자 포트폴리오 / 댓글 게시판
신입 웹 개발자 포트폴리오 / 댓글 게시판신입 웹 개발자 포트폴리오 / 댓글 게시판
신입 웹 개발자 포트폴리오 / 댓글 게시판
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
Introducing Playwright's New Test Runner
Introducing Playwright's New Test RunnerIntroducing Playwright's New Test Runner
Introducing Playwright's New Test Runner
 
Junit
JunitJunit
Junit
 
FME:23 for the Enterprise - A Deep Dive into Key New Features
FME:23 for the Enterprise - A Deep Dive into Key New FeaturesFME:23 for the Enterprise - A Deep Dive into Key New Features
FME:23 for the Enterprise - A Deep Dive into Key New Features
 
Django
DjangoDjango
Django
 

En vedette

JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
Nicholas Zakas
 
Good Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas CrockfordGood Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas Crockford
rajivmordani
 
High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)
Nicholas Zakas
 

En vedette (20)

Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
 
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
 
Douglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your BrainDouglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your Brain
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
The JSON Saga
The JSON SagaThe JSON Saga
The JSON Saga
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
 
Performance, Games, and Distributed Testing in JavaScript
Performance, Games, and Distributed Testing in JavaScriptPerformance, Games, and Distributed Testing in JavaScript
Performance, Games, and Distributed Testing in JavaScript
 
Performance Improvements in Browsers
Performance Improvements in BrowsersPerformance Improvements in Browsers
Performance Improvements in Browsers
 
Douglas Crockford - Ajax Security
Douglas Crockford - Ajax SecurityDouglas Crockford - Ajax Security
Douglas Crockford - Ajax Security
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
Json
JsonJson
Json
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
 
Good Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas CrockfordGood Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas Crockford
 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
 
JavaScript Variable Performance
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable Performance
 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at Google
 
High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)
 
Responsive interfaces
Responsive interfacesResponsive interfaces
Responsive interfaces
 

Similaire à Speed Up Your JavaScript

Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014
Pharo
 
Firefox 3.1 in 3.1 minutes
Firefox 3.1 in 3.1 minutesFirefox 3.1 in 3.1 minutes
Firefox 3.1 in 3.1 minutes
Thomas Bassetto
 
[E4]triple s deview
[E4]triple s deview[E4]triple s deview
[E4]triple s deview
NAVER D2
 
Bottlenecks, Bottlenecks, and more Bottlenecks: Lessons Learned from 2 Years ...
Bottlenecks, Bottlenecks, and more Bottlenecks: Lessons Learned from 2 Years ...Bottlenecks, Bottlenecks, and more Bottlenecks: Lessons Learned from 2 Years ...
Bottlenecks, Bottlenecks, and more Bottlenecks: Lessons Learned from 2 Years ...
Enkitec
 
Supercharging Cassandra - GOTO Amsterdam
Supercharging Cassandra - GOTO AmsterdamSupercharging Cassandra - GOTO Amsterdam
Supercharging Cassandra - GOTO Amsterdam
Acunu
 
Real world Scala hAkking NLJUG JFall 2011
Real world Scala hAkking NLJUG JFall 2011Real world Scala hAkking NLJUG JFall 2011
Real world Scala hAkking NLJUG JFall 2011
Raymond Roestenburg
 

Similaire à Speed Up Your JavaScript (20)

Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014
 
Firefox 3.1 in 3.1 minutes
Firefox 3.1 in 3.1 minutesFirefox 3.1 in 3.1 minutes
Firefox 3.1 in 3.1 minutes
 
Fosdem 13: Pharo 2.0 update
Fosdem 13: Pharo 2.0 updateFosdem 13: Pharo 2.0 update
Fosdem 13: Pharo 2.0 update
 
[E4]triple s deview
[E4]triple s deview[E4]triple s deview
[E4]triple s deview
 
Firefox 3.5 Overview
Firefox 3.5 OverviewFirefox 3.5 Overview
Firefox 3.5 Overview
 
Toster - Understanding the Rails Web Model and Scalability Options
Toster - Understanding the Rails Web Model and Scalability OptionsToster - Understanding the Rails Web Model and Scalability Options
Toster - Understanding the Rails Web Model and Scalability Options
 
Understanding the Rails web model and scalability options
Understanding the Rails web model and scalability optionsUnderstanding the Rails web model and scalability options
Understanding the Rails web model and scalability options
 
Bottlenecks, Bottlenecks, and more Bottlenecks: Lessons Learned from 2 Years ...
Bottlenecks, Bottlenecks, and more Bottlenecks: Lessons Learned from 2 Years ...Bottlenecks, Bottlenecks, and more Bottlenecks: Lessons Learned from 2 Years ...
Bottlenecks, Bottlenecks, and more Bottlenecks: Lessons Learned from 2 Years ...
 
Supercharging Cassandra - GOTO Amsterdam
Supercharging Cassandra - GOTO AmsterdamSupercharging Cassandra - GOTO Amsterdam
Supercharging Cassandra - GOTO Amsterdam
 
ずばり動く!kumofs と ずばり動かないケース
ずばり動く!kumofs と ずばり動かないケースずばり動く!kumofs と ずばり動かないケース
ずばり動く!kumofs と ずばり動かないケース
 
NPW2009 - my.opera.com scalability v2.0
NPW2009 - my.opera.com scalability v2.0NPW2009 - my.opera.com scalability v2.0
NPW2009 - my.opera.com scalability v2.0
 
Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014
 
Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014
 
Real world Scala hAkking NLJUG JFall 2011
Real world Scala hAkking NLJUG JFall 2011Real world Scala hAkking NLJUG JFall 2011
Real world Scala hAkking NLJUG JFall 2011
 
The More Capable Series 40 Java Platform
The More Capable Series 40 Java PlatformThe More Capable Series 40 Java Platform
The More Capable Series 40 Java Platform
 
分散Key-valueストアkumofsの思想と設計
分散Key-valueストアkumofsの思想と設計分散Key-valueストアkumofsの思想と設計
分散Key-valueストアkumofsの思想と設計
 
Firefox 4 and more
Firefox 4 and moreFirefox 4 and more
Firefox 4 and more
 
Flink Forward Berlin 2017: Robert Metzger - Keep it going - How to reliably a...
Flink Forward Berlin 2017: Robert Metzger - Keep it going - How to reliably a...Flink Forward Berlin 2017: Robert Metzger - Keep it going - How to reliably a...
Flink Forward Berlin 2017: Robert Metzger - Keep it going - How to reliably a...
 
Spark streaming + kafka 0.10
Spark streaming + kafka 0.10Spark streaming + kafka 0.10
Spark streaming + kafka 0.10
 
TWaver Flex Performance Report
TWaver Flex Performance ReportTWaver Flex Performance Report
TWaver Flex Performance Report
 

Plus de Nicholas Zakas

Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas
 

Plus de Nicholas Zakas (20)

Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
 
The Pointerless Web
The Pointerless WebThe Pointerless Web
The Pointerless Web
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)
 
High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! Homepage
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI Compressor
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 
The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3
 
Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)
 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Speed Up Your JavaScript

  • 1. Speed Up Your JavaScript Nicholas C. Zakas Principal Front End Engineer, Yahoo! x Web E ponents – June 4, 2009
  • 2. Who's this guy? • Principal Front End Engineer, Yahoo! Homepage • YUI Contributor • Author
  • 3.
  • 6. No
  • 7. No compilation!* * Humor me for now. It'll make this easier.
  • 9. Who will help your code?
  • 10.
  • 11. JavaScript Performance Issues • Scope management • Data access • Loops • DOM
  • 12.
  • 14. 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
  • 15. Execution Context Identifier Resolution • Start at scope chain position 0 • If not found go to position 1 • Rinse, repeat
  • 16. Identifier Resolution • Local variables = fast! • The further into the chain, the slower the resolution
  • 17. Identifier Resolution (Reads) 200 180 160 140 Firefox 3 Time (ms) per 200,000 reads Firefox 3.1 Beta 3 120 Chrome 1 Chrome 2 Beta Internet Explorer 7 100 Internet Explorer 8 Opera 9.64 80 Opera 10 Alpha Safari 3.2 Safari 4 Beta 60 40 20 0 1 2 3 4 5 6 Identifier Depth
  • 18. Identifier Resolution (Writes) 200 180 160 140 Firefox 3 Time (ms) per 200,000 writes Firefox 3.1 Beta 3 120 Chrome 1 Chrome 2 Beta Internet Explorer 7 100 Internet Explorer 8 Opera 9.64 80 Opera 10 Alpha Safari 3.2 Safari 4 Beta 60 40 20 0 1 2 3 4 5 6 Identifier Depth
  • 19. Scope Chain Augmentation • The with statement • The catch clause of try-catch • Both add an object to the front of the scope chain
  • 20. Inside of Global Function
  • 21. Inside of with/catch Statement • Local variables now in second slot • with variables now in first slot
  • 23. Closures • The [[Scope]] property of closures begins with two objects • Calling the closure means three objects in the scope chain (minimum)
  • 24.
  • 27. 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
  • 28.
  • 29. JavaScript Performance Issues • Scope management • Data access • Loops • DOM
  • 30. Places to Access Data • Literal value • Variable • Object property • Array item
  • 31. 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
  • 32. 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.1 Chrome 1 Chrome 2 Internet Internet Opera 9.64 Opera 10 Safari 3.2 Safari 4 Beta 3 Beta Explorer 7 Explorer 8 Alpha Beta
  • 33. Property Depth • object.name < object.name.name • The deeper the property, the longer it takes to retrieve
  • 34. Property Depth 250 200 Firefox 3 Time (ms) per 200,000 reads Firefox 3.1 Beta 3 150 Chrome 1 Chrome 2 Beta Internet Explorer 7 Internet Explorer 8 Opera 9.64 100 Opera 10 Alpha Safari 3.2 Safari 4 Beta 50 0 1 2 3 4 Property Depth
  • 35. Property Notation • Difference between object.name and object[“name”]? – Generally no – Exception: Dot notation is faster in Safari
  • 36. 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
  • 37.
  • 38. -5% -10% -33%
  • 39. JavaScript Performance Issues • Scope management • Data Access • Loops • DOM
  • 40. Loops • ECMA-262, 3rd Edition: – for – for-in – do-while – while • ECMA-357, 2nd Edition: – for each
  • 41.
  • 44. 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
  • 45. Fixing Loops • Decrease amount of work per iteration • Decrease number of iterations
  • 46.
  • 47.
  • 48.
  • 49. Easy Fixes • Eliminate object property/array item lookups
  • 50.
  • 51. Easy Fixes • Eliminate object property/array item lookups • Combine control condition and control variable change – Work avoidance!
  • 52. Two evaluations: j < len j < len == true
  • 54. Easy Fixes • Eliminate object property/array item lookups • Combine control condition and control variable change – Work avoidance!
  • 55. 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()
  • 56. • Introduces additional function • Function requires execution (execution context created, destroyed) • Function also creates additional object in scope chain 8x
  • 57. JavaScript Performance Issues • Scope management • Data Access • Loops • DOM
  • 58. DOM
  • 60. HTMLCollection Objects • document.images, document.forms, etc. • getElementsByTagName() • getElementsByClassName()
  • 61. Note: Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed.
  • 63. 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
  • 64. 15x 53x 68x
  • 65. = = =
  • 66. 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
  • 67. 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; }
  • 69. Reflow is the process by which the geometry of the layout engine's formatting objects are computed. - Chris Waterson, Mozilla
  • 70. When Reflow? • Initial page load • Browser window resize • DOM nodes added or removed • Layout styles applied • Layout information retrieved
  • 72. DocumentFragment • A document-like object • Not visually represented • Considered a child of the document from which it was created • When passed to addChild(), appends all of its children rather than itself
  • 73. No reflow! Reflow!
  • 74. When Reflow? • Initial page load • Browser window resize • DOM nodes added or removed • Layout styles applied • Layout information retrieved
  • 75. Reflow! Reflow! Reflow!
  • 76. What to do? • Minimize changes on style property • Define CSS class with all changes and just change className property
  • 78. When Reflow? • Initial page load • Browser window resize • DOM nodes added or removed • Layout styles applied • Layout information retrieved – Only if reflow is cached
  • 79. Reflow? Reflow? Reflow?
  • 80. What to do? • Minimize access to layout information • If a value is used more than once, store in local variable
  • 81. Speed Up Your DOM • Be careful using HTMLCollection objects • Perform DOM manipulations off the document • Change CSS classes, not CSS styles • Be careful when accessing layout information
  • 82.
  • 83. Will it be like this forever?
  • 84. No
  • 85. 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.
  • 87. Summary • Mind your scope • Local variables are your friends • Function execution comes at a cost • Keep loops small • Avoid doing work whenever possible • Minimize DOM interaction • Use a good browser and encourage others to do the same
  • 89. Etcetera • My blog: www.nczonline.net • My email: nzakas@yahoo-inc.com • Twitter: @slicknet
  • 90. Creative Commons Images Used • http://www.flickr.com/photos/blackbutterfly/3051019058/ • http://www.flickr.com/photos/23816315@N07/2528296337/ • http://www.flickr.com/photos/37287477@N00/515178157/ • http://www.flickr.com/photos/ottoman42/455242/ • http://www.flickr.com/photos/crumbs/2702429363/ • http://flickr.com/photos/oberazzi/318947873/