SlideShare a Scribd company logo
1 of 90
Download to read offline
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/

More Related Content

What's hot

Cours c#
Cours c#Cours c#
Cours c#zan
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
Programmation orientée objet avancée
Programmation orientée objet avancéeProgrammation orientée objet avancée
Programmation orientée objet avancéeMahfoud EL HOUDAIGUI
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
P1 introduction à android
P1 introduction à androidP1 introduction à android
P1 introduction à androidLilia Sfaxi
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHubJames Gray
 
SignalR for ASP.NET Developers
SignalR for ASP.NET DevelopersSignalR for ASP.NET Developers
SignalR for ASP.NET DevelopersShivanand Arur
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking frameworkPhat VU
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsScott Gardner
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Building Cloud-Native Applications with Helidon
Building Cloud-Native Applications with HelidonBuilding Cloud-Native Applications with Helidon
Building Cloud-Native Applications with HelidonDmitry Kornilov
 

What's hot (20)

Cours c#
Cours c#Cours c#
Cours c#
 
Selenium Locators
Selenium LocatorsSelenium Locators
Selenium Locators
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
Introduction to git
Introduction to gitIntroduction to git
Introduction to git
 
Programmation orientée objet avancée
Programmation orientée objet avancéeProgrammation orientée objet avancée
Programmation orientée objet avancée
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
P1 introduction à android
P1 introduction à androidP1 introduction à android
P1 introduction à android
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHub
 
Support Web Services SOAP et RESTful Mr YOUSSFI
Support Web Services SOAP et RESTful Mr YOUSSFISupport Web Services SOAP et RESTful Mr YOUSSFI
Support Web Services SOAP et RESTful Mr YOUSSFI
 
JavaScript
JavaScriptJavaScript
JavaScript
 
SignalR for ASP.NET Developers
SignalR for ASP.NET DevelopersSignalR for ASP.NET Developers
SignalR for ASP.NET Developers
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Support JEE Spring Inversion de Controle IOC et Spring MVC
Support JEE Spring Inversion de Controle IOC et Spring MVCSupport JEE Spring Inversion de Controle IOC et Spring MVC
Support JEE Spring Inversion de Controle IOC et Spring MVC
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
 
Angular
AngularAngular
Angular
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Building Cloud-Native Applications with Helidon
Building Cloud-Native Applications with HelidonBuilding Cloud-Native Applications with Helidon
Building Cloud-Native Applications with Helidon
 

Viewers also liked

Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Nicholas Zakas
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScriptNicholas Zakas
 
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceNicholas Zakas
 
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 BrainWeb Directions
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
The JSON Saga
The JSON SagaThe JSON Saga
The JSON Sagakaven yan
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performancekaven yan
 
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 JavaScriptjeresig
 
Performance Improvements in Browsers
Performance Improvements in BrowsersPerformance Improvements in Browsers
Performance Improvements in Browsersjeresig
 
Douglas Crockford - Ajax Security
Douglas Crockford - Ajax SecurityDouglas Crockford - Ajax Security
Douglas Crockford - Ajax SecurityWeb Directions
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Libraryjeresig
 
Good Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas CrockfordGood Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas Crockfordrajivmordani
 
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)Nicholas Zakas
 
JavaScript Variable Performance
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable PerformanceNicholas Zakas
 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas Zakas
 
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
 

Viewers also liked (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
 

Similar to Speed Up Your JavaScript

Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo
 
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 minutesThomas Bassetto
 
Fosdem 13: Pharo 2.0 update
Fosdem 13: Pharo 2.0 updateFosdem 13: Pharo 2.0 update
Fosdem 13: Pharo 2.0 updateMarcus Denker
 
[E4]triple s deview
[E4]triple s deview[E4]triple s deview
[E4]triple s deviewNAVER D2
 
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 OptionsFabio Akita
 
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.toster
 
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 AmsterdamAcunu
 
ずばり動く!kumofs と ずばり動かないケース
ずばり動く!kumofs と ずばり動かないケースずばり動く!kumofs と ずばり動かないケース
ずばり動く!kumofs と ずばり動かないケースSadayuki Furuhashi
 
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.0Cosimo Streppone
 
Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014ESUG
 
Pharo Status ESUG 2014
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014Marcus Denker
 
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 2011Raymond Roestenburg
 
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 PlatformGorkem Ercan
 
分散Key-valueストアkumofsの思想と設計
分散Key-valueストアkumofsの思想と設計分散Key-valueストアkumofsの思想と設計
分散Key-valueストアkumofsの思想と設計Sadayuki Furuhashi
 
Firefox 4 and more
Firefox 4 and moreFirefox 4 and more
Firefox 4 and moredynamis
 
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...Flink Forward
 
TWaver Flex Performance Report
TWaver Flex Performance ReportTWaver Flex Performance Report
TWaver Flex Performance Report253725291
 

Similar to 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
 

More from 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 MenaceNicholas Zakas
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!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
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Nicholas Zakas
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)Nicholas Zakas
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011Nicholas Zakas
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed BumpsNicholas Zakas
 
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)Nicholas Zakas
 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)Nicholas Zakas
 
High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010Nicholas Zakas
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010Nicholas Zakas
 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! HomepageNicholas Zakas
 
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 2010Nicholas Zakas
 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorNicholas Zakas
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScriptNicholas Zakas
 
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 3Nicholas Zakas
 
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)Nicholas Zakas
 
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)Nicholas Zakas
 

More from 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)
 

Recently uploaded

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Recently uploaded (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

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/