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

Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in JavaRavi_Kant_Sahu
 
Asynchronous Programming at Netflix
Asynchronous Programming at NetflixAsynchronous Programming at Netflix
Asynchronous Programming at NetflixC4Media
 
Oracle APEX Introduction (release 18.1)
Oracle APEX Introduction (release 18.1)Oracle APEX Introduction (release 18.1)
Oracle APEX Introduction (release 18.1)Michael Hichwa
 
Enterprise java unit-1_chapter-2
Enterprise java unit-1_chapter-2Enterprise java unit-1_chapter-2
Enterprise java unit-1_chapter-2sandeep54552
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstMd. Aftab Uddin Kajal
 
Agile Test Management Using Jira and Zephyr
Agile Test Management Using Jira and ZephyrAgile Test Management Using Jira and Zephyr
Agile Test Management Using Jira and ZephyrXBOSoft
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetJava JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetMark Papis
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework XtextSebastian Zarnekow
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Multiple inheritance in java3 (1).pptx
Multiple inheritance in java3 (1).pptxMultiple inheritance in java3 (1).pptx
Multiple inheritance in java3 (1).pptxRkGupta83
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing DroolsMario Fusco
 

What's hot (20)

Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Asynchronous Programming at Netflix
Asynchronous Programming at NetflixAsynchronous Programming at Netflix
Asynchronous Programming at Netflix
 
Oracle APEX Introduction (release 18.1)
Oracle APEX Introduction (release 18.1)Oracle APEX Introduction (release 18.1)
Oracle APEX Introduction (release 18.1)
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Enterprise java unit-1_chapter-2
Enterprise java unit-1_chapter-2Enterprise java unit-1_chapter-2
Enterprise java unit-1_chapter-2
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code first
 
Agile Test Management Using Jira and Zephyr
Agile Test Management Using Jira and ZephyrAgile Test Management Using Jira and Zephyr
Agile Test Management Using Jira and Zephyr
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetJava JVM Memory Cheat Sheet
Java JVM Memory Cheat Sheet
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework Xtext
 
Drools rule Concepts
Drools rule ConceptsDrools rule Concepts
Drools rule Concepts
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Multiple inheritance in java3 (1).pptx
Multiple inheritance in java3 (1).pptxMultiple inheritance in java3 (1).pptx
Multiple inheritance in java3 (1).pptx
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 

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

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

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
 
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 (19)

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

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
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
 
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
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
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
 
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
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
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
 

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/