SlideShare a Scribd company logo
1 of 50
Download to read offline
Blog http://blogs.msdn.com/dorischen
Who am I?
 Developer Evangelist at Microsoft based in Silicon Valley, CA
 Blog: http://blogs.msdn.com/b/dorischen/
 Twitter @doristchen
 Email: doris.chen@microsoft.com
 Has over 15 years of experience in the software industry focusing
on web technologies
 Spoke and published widely at JavaOne, O'Reilly, Silicon Valley
Code Camp, SD West, SD Forum and worldwide User Groups
meetings
 Doris received her Ph.D. from the University of California at Los
Angeles (UCLA)
PAGE 2
Tips & tricks that still work
http://channel9.msdn.com/Events/Build/2012/3-132
Raw JS code: http://aka.ms/FastJS
Demo
HighFive
Arrays
Objects and
properties
Numbers Animation loop
Memory allocations
Repeat until neighbors list empty
Components and control flow
Always start with a good profiler
Windows Performance Toolkit
http://aka.ms/WinPerfKit
F12 UI Responsiveness Tool
Writing fast sites & apps with JavaScript
Understandandtargetmodernengines
• Principle#1: Stay lean – use less memory
• Principle#2: Use fast objects and do fast manipulations
• Principle#3: Write fast arithmetic
• Principle#4: Use fast arrays
• Principle#5: Do less (cross-subsystem) work
Do we expect so much of GC to happen?
GC
What triggers a garbage collection?
• Every call to new or implicit memory allocation reserves GC memory
- Allocations are cheap until current pool is exhausted
• When the pool is exhausted, engines force a collection
- Collections cause program pauses
- Pauses could take milliseconds
• Be careful with object allocation patterns in your apps
- Every allocation brings you closer to a GC pause
Best practices for staying lean
• Avoid unnecessary object creation
• Use object pools, when possible
• Be aware of allocation patterns
- Setting closures to event handlers
- Dynamically creating DOM (sub) trees
- Implicit allocations in the engine
Results
• Overall FG GC time reduced to 1/3rd
• Raw JavaScript perf improved ~3x
Internal Type System: Fast Object Types
var p1;
p1.north = 1;
p1.south = 0;
var p2;
p2.south = 0;
p2.north = 1;
north 1
south 0
north 1
south 0
north 1
south 0
Base Type “{}”
Type “{north}” Type “{south}”
Base Type “{}”
Type “{south, north}”Type “{north, south}”
Create fast types and avoid type mismatches
Don’t add properties conditionally
function Player(direction) {
if (direction = “NE”) {
this.n = 1;
this.e = 1;
}
else if (direction = “ES”) {
this.e = 1;
this.s = 1;
}
...
}
var p1 = new Player(“NE”); // p1 type {n,e}
var p2 = new Player(“ES”); // p2 type {e,s}
function Player(north,east,south,west) {
this.n = north;
this.e = east;
this.s = south;
this.w = west;
}
var p1 = new Player(1,1,0,0);//p1 type {n,e,s,w}
var p2 = new Player(0,0,1,1);//p2 type {n,e,s,w}
p1.type != p2.type p1.type == p2.type
Avoid conversion from fast type to slower property bags
Deleting properties forces conversion
function Player(north,east,south,west) {
this.n = north;
this.e = east;
this.s = south;
this.w = west;
}
var p1 = new Player();
delete p1.n;
function Player(north,east,south,west) {
this.n = north;
this.e = east;
this.s = south;
this.w = west;
}
var p1 = new Player();
p1.n = 0; // or undefined
SLOW FAST
Avoid creating slower property bags
Restrict using getters, setters and property descriptors in perf critical paths
function Player(north, east, south, west) {
Object.defineProperty(this, "n", {
get : function() { return nVal; },
set : function(value) { nVal=value; },
enumerable: true, configurable: true
});
Object.defineProperty(this, "e", {
get : function() { return eVal; },
set : function(value) { eVal=value; },
enumerable: true, configurable: true
});
...
}
var p = new Player(1,1,0,0);
var n = p.n;
p.n = 0;
...
function Player(north, east, south, west) {
this.n = north;
this.e = east;
this.s = south;
this.w = west;
...
}
var p = new Player(1,1,0,0);
var n = p.n;
p.n = 0;
...
SLOW FAST
demo
Results
• Time in script execution reduced ~30%
• Raw JS performance improved ~30%
3.8s 2.2s
Best practices for fast objects and manipulations
• Create and use fast types
• Keep shapes of objects consistent
• Avoid type mismatches for fast types
Numbers in JavaScript
• All numbers are IEEE 64-bit floating point numbers
- Great for flexibility
- Performance and optimization challenge
31bits
31-bit (tagged) Integers
1bit
1
31bits
Object pointer
1bit
0
32bits
32bits
Floats
32-bit Integers
STACK HEAP
FIXED LENGTH, FASTER ACCESS VARIABLE LENGTH, SLOWER ACCESS
Boxed
Avoid creating floats if they are not needed
Fastest way to indicate integer math is |0
var r = 0;
function doMath(){
var a = 5;
var b = 2;
r = ((a + b) / 2) |0 ; // r = 3
r = Math.round((a + b) / 2); // r = 4
}
var r = 0;
function doMath(){
var a = 5;
var b = 2;
r = ((a + b) / 2); // r = 3.5
}
...
var intR = Math.floor(r);
0x005e4148r: 0x00000007r:
0x00000009r:
Number
3.5
STACK HEAP STACK
SLOW FAST
SLOW
Take advantage of type-specialization for arithmetic
Create separate functions for ints and floats; use consistent argument types
function Distance(p1, p2) {
var dx = p1.x - p2.x;
var dy = p1.y - p2.y;
var d2 = dx * dx + dy * dy;
return Math.sqrt(d2);
}
var point1 = {x:10, y:10};
var point2 = {x:20, y:20};
var point3 = {x:1.5, y:1.5};
var point4 = {x:0x0AB, y:0xBC};
Distance(point1, point3);
Distance(point2, point4);
function DistanceFloat(p1, p2) {
var dx = p1.x - p2.x;
var dy = p1.y - p2.y;
var d2 = dx * dx + dy * dy;
return Math.sqrt(d2);
}
function DistanceInt(p1,p2) {
var dx = p1.x - p2.x;
var dy = p1.y - p2.y;
var d2 = dx * dx + dy * dy;
return (Math.sqrt(d2) | 0);
}
var point1 = {x:10, y:10};
var point2 = {x:20, y:20};
var point3 = {x:1.5, y:1.5};
var point4 = {x:0x0AB, y:0xBC};
DistanceInt(point1, point2);
DistanceFloat(point3, point4);
SLOW FAST
Best practices for fast arithmetic
• Use 31-bit integer math when possible
• Avoid floats if they are not needed
• Design for type specialized arithmetic
Pre-allocate arrays
var a = new Array(100);
for (var i = 0; i < 100; i++) {
a[i] = i + 2;
}
var a = new Array();
for (var i = 0; i < 100; i++) {
a.push(i + 2);
}
0 ?
?+1 ??
…0 100
SLOW FAST
var a = new Array(100000);
for (var i = 0; i < a.length; i++) {
a[i] = i;
}
...
//operations on the array
...
a[99] = “str”;
For mixed arrays, provide an early hint
Avoid delayed type conversion and copy
var a = new Array(100000);
a[0] = “hint”;
for (var i = 0; i < a.length; i++) {
a[i] = i;
}
...
//operations on the array
...
a[99] = “str”;
SLOW FAST
Keep values in arrays consistent
Numeric arrays treated like Typed Arrays internally
var a = [1,0x2,99.1,5]; //mixed array
var b = [0x10,8,9]; //mixed array
function add(a,i,b,j)
{
return a[i] + b[j];
}
add(a,0,b,0);
add(a,1,b,1);
var a = [1,5,8,9]; //int array
var b = [0x02,0x10,99.1]; //float
array
function add(a,i,b,j)
{
return a[i] + b[j];
}
add(a,0,b,0);
add(a,1,b,1);
SLOW FAST
Keep arrays dense
Deleting elements can force type change and de-optimization
var a = new Array(1000); //type int
...
for (var i = 0; i < boardSize; i++) {
matrix[i] = [1,1,0,0];
}
//operating on the array
...
delete matrix[23];
...
//operating on the array
var a = new Array(1000); //type int
...
for (var i = 0; i < boardSize; i++) {
matrix[i] = [1,1,0,0];
}
//operating on the array
...
matrix[23] = 0;
...
//operating on the array
SLOW FAST
Enumerate arrays efficiently
Explicit caching of length avoids repetitive property accesses
var a = new Array(100);
var total = 0;
for (var item in a) {
total += item;
};
a.forEach(function(item){
total += item;
});
for (var i = 0; i < a.length; i++) {
total += a[i];
}
var a = new Array(100);
var total = 0;
cachedLength = a.length;
for (var i = 0; i < cachedLength; i++) {
total += a[i];
}
SLOW FAST
Best practices for using arrays efficiently
• Pre-allocate arrays
• Keep array type consistent
• Use typed arrays when possible
• Keep arrays dense
• Enumerate arrays efficiently
Avoid chattiness with the DOM
...
//for each rotation
document.body.game.getElementById(elID).classList.remove(oldClass)
document.body.game.getElementById(elID).classList.add(newClass)
...
var element = document.getElementById(elID).classList;
//for each rotation
element.remove(oldClass)
element.add(newClass)
...
JavaScript
DOM
JavaScript
DOM
Avoid automatic conversions of DOM values
Values from DOM are strings by default
this.boardSize = document.getElementById("benchmarkBox").value;
for (var i = 0; i < this.boardSize; i++) { //this.boardSize is
“25”
for (var j = 0; j < this.boardSize; j++) { //this.boardSize is
“25”
...
}
}
this.boardSize = parseInt(document.getElementById("benchmarkBox").value);
for (var i = 0; i < this.boardSize; i++) { //this.boardSize is 25
for (var j = 0; j < this.boardSize; j++) { //this.boardSize is 25
...
}
}
FAST
(25% marshalling cost
reduction in init function)
SLOW
Paint as much as your users can see
Align timers to display frames
setInterval(animate, 0);
setTimeout(animate, 0);
requestAnimationFrame(animate);
setInterval(animate, 1000 / 60);
setTimeout(animate, 1000 / 60);
MORE WORK LESS WORK
demo
Results
Save CPU cycles
75% 65%
setTimeout(animate, 0); requestAnimationFrame(animate);
Optimized JS code: http://aka.ms/FasterJS
Overview Concepts
High Performance Websites
Steve Souders, September 2007
Event Faster Websites: Best Practices
Steve Souders, June 2009
High Performance Browser Networking
Ilya Grigorik, September 2013
JavaScript Patterns
High Performance JavaScript
Nicholas Zakas, March 2010
JavaScript the Good Parts
Douglas Crockford, May 2008
JavaScript Patterns
Stoyan Stefanov, September 2010
JavaScript Cookbook
Shelley Powers, July 2010
Microsoft Guidance
Windows Store App: JavaScript Best Practices
MSDN, December 2012
Performance Tricks to Make Apps & Sites Faster
Jatinder Mann, Build 2012
50 Performance Tricks for Windows Store Apps
Jason Weber, Build 2011
Engineering Excellence Performance Guidance
Jason Weber, EE Forum 2011
Internet Explorer Architectural Overview
Jason Weber, PDC 2011
W3C Web Performance
Web Performance Working Group Homepage
Navigation Timing Specification
Blog Posts
1) Measuring Performance with ETW/XPerf
2) Measuring Performance in Lab Environments
3) Browser Subsystems Overview
4) What Common Benchmarks Measure
Tools
Windows Performance Toolkit
Fiddler Web Debugger
Contact
Doris Chen
Twitter: @doristchen
Email: doris.chen@Microsoft.com
http://bit.ly/win8OnePage
http://bit.ly/HTML5Wins8Camp
http://msdn.microsoft.com/en-us/library/windows/apps/hh465194.aspx
http://Aka.ms/brockschmidtbook
 http:/dev.windows.com
PAGE
PAGE
• Responsive Web Design and CSS3
• http://bit.ly/CSS3Intro
• HTML5, CSS3 Free 1 Day Training
• http://bit.ly/HTML5DevCampDownload
• Using Blend to Design HTML5 Windows 8 Application (Part II): Style,
Layout and Grid
• http://bit.ly/HTML5onBlend2
• Using Blend to Design HTML5 Windows 8 Application (Part III): Style
Game Board, Cards, Support Different Device, View States
• http://bit.ly/HTML5onBlend3
• Feature-specific demos
• http://ie.microsoft.com/testdrive/
• Real-world demos
• http://www.beautyoftheweb.com/
Microsoft BizSpark
Software
• Three year access to current,
full-featured software
development tools
• $150 of monthly Windows
Azure benefits and discounted
rates to quickly build, deploy
and manage web applications
• Professional technical and
product support
• Unique and valuable offers
from the BizSpark Network
Partners to help run your
business
• Four free MSDN Support
Incidents.
• Profile, Offers and Events
• A connection to the BizSpark
ecosystem, giving startups
access to investors, advisors
and mentors
• Opportunities to achieve
marketing visibility
Support Visibility
Microsoft BizSpark is a global program that provides free software,
support and visibility to help startups succeed. There are 50K startups
in BizSpark in 100+ countries. The three year program is free of charge
and gives startups:

More Related Content

What's hot

High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scaladjspiewak
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeManoj Kumar
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP LanguageAhmed Ali
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUIBongwon Lee
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-CKazunobu Tasaka
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless Jared Roesch
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldWerner Hofstra
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 
C++ nothrow movable types
C++ nothrow movable typesC++ nothrow movable types
C++ nothrow movable typesarvidn
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.Ruslan Shevchenko
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections LibraryPaul Phillips
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1Hackraft
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idrisConor Farrell
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.Brian Hsu
 

What's hot (20)

High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik Cube
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP Language
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
C++ nothrow movable types
C++ nothrow movable typesC++ nothrow movable types
C++ nothrow movable types
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idris
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 

Similar to Optimizing JavaScript for Speed and Performance

Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Doris Chen
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scalaXing
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of JavascriptUniverse41
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp fullVõ Hòa
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyRalph Johnson
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesJamund Ferguson
 
Functional Operations - Susan Potter
Functional Operations - Susan PotterFunctional Operations - Susan Potter
Functional Operations - Susan Potterdistributed matters
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays kinan keshkeh
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersRick Beerendonk
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 

Similar to Optimizing JavaScript for Speed and Performance (20)

Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
 
Functional Operations - Susan Potter
Functional Operations - Susan PotterFunctional Operations - Susan Potter
Functional Operations - Susan Potter
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Java introduction
Java introductionJava introduction
Java introduction
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 

More from Doris Chen

Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Doris Chen
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work EverywhereDoris Chen
 
Angular mobile angular_u
Angular mobile angular_uAngular mobile angular_u
Angular mobile angular_uDoris Chen
 
Lastest Trends in Web Development
Lastest Trends in Web DevelopmentLastest Trends in Web Development
Lastest Trends in Web DevelopmentDoris Chen
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Doris Chen
 
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterPractical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterDoris Chen
 
What Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsWhat Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsDoris Chen
 
Windows 8 Opportunity
Windows 8 OpportunityWindows 8 Opportunity
Windows 8 OpportunityDoris Chen
 
Wins8 appfoforweb fluent
Wins8 appfoforweb fluentWins8 appfoforweb fluent
Wins8 appfoforweb fluentDoris Chen
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Doris Chen
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsDoris Chen
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Doris Chen
 
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Doris Chen
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3Doris Chen
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Doris Chen
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It TodayDoris Chen
 
Dive Into HTML5
Dive Into HTML5Dive Into HTML5
Dive Into HTML5Doris Chen
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It TodayDoris Chen
 
HTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and DesktopHTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and DesktopDoris Chen
 
Dive into HTML5: SVG and Canvas
Dive into HTML5: SVG and CanvasDive into HTML5: SVG and Canvas
Dive into HTML5: SVG and CanvasDoris Chen
 

More from Doris Chen (20)

Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work Everywhere
 
Angular mobile angular_u
Angular mobile angular_uAngular mobile angular_u
Angular mobile angular_u
 
Lastest Trends in Web Development
Lastest Trends in Web DevelopmentLastest Trends in Web Development
Lastest Trends in Web Development
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterPractical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
 
What Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsWhat Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS Apps
 
Windows 8 Opportunity
Windows 8 OpportunityWindows 8 Opportunity
Windows 8 Opportunity
 
Wins8 appfoforweb fluent
Wins8 appfoforweb fluentWins8 appfoforweb fluent
Wins8 appfoforweb fluent
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 Apps
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
 
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 
Dive Into HTML5
Dive Into HTML5Dive Into HTML5
Dive Into HTML5
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 
HTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and DesktopHTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and Desktop
 
Dive into HTML5: SVG and Canvas
Dive into HTML5: SVG and CanvasDive into HTML5: SVG and Canvas
Dive into HTML5: SVG and Canvas
 

Recently uploaded

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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
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
 
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
 
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
 
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
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
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
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
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
 

Recently uploaded (20)

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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
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
 
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
 
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
 
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
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
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
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
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
 

Optimizing JavaScript for Speed and Performance

  • 1.
  • 2. Blog http://blogs.msdn.com/dorischen Who am I?  Developer Evangelist at Microsoft based in Silicon Valley, CA  Blog: http://blogs.msdn.com/b/dorischen/  Twitter @doristchen  Email: doris.chen@microsoft.com  Has over 15 years of experience in the software industry focusing on web technologies  Spoke and published widely at JavaOne, O'Reilly, Silicon Valley Code Camp, SD West, SD Forum and worldwide User Groups meetings  Doris received her Ph.D. from the University of California at Los Angeles (UCLA) PAGE 2
  • 3.
  • 4.
  • 5. Tips & tricks that still work http://channel9.msdn.com/Events/Build/2012/3-132
  • 6.
  • 7. Raw JS code: http://aka.ms/FastJS
  • 9. Arrays Objects and properties Numbers Animation loop Memory allocations Repeat until neighbors list empty Components and control flow
  • 10. Always start with a good profiler Windows Performance Toolkit http://aka.ms/WinPerfKit F12 UI Responsiveness Tool
  • 11.
  • 12. Writing fast sites & apps with JavaScript Understandandtargetmodernengines • Principle#1: Stay lean – use less memory • Principle#2: Use fast objects and do fast manipulations • Principle#3: Write fast arithmetic • Principle#4: Use fast arrays • Principle#5: Do less (cross-subsystem) work
  • 13.
  • 14. Do we expect so much of GC to happen? GC
  • 15. What triggers a garbage collection? • Every call to new or implicit memory allocation reserves GC memory - Allocations are cheap until current pool is exhausted • When the pool is exhausted, engines force a collection - Collections cause program pauses - Pauses could take milliseconds • Be careful with object allocation patterns in your apps - Every allocation brings you closer to a GC pause
  • 16. Best practices for staying lean • Avoid unnecessary object creation • Use object pools, when possible • Be aware of allocation patterns - Setting closures to event handlers - Dynamically creating DOM (sub) trees - Implicit allocations in the engine
  • 17. Results • Overall FG GC time reduced to 1/3rd • Raw JavaScript perf improved ~3x
  • 18.
  • 19. Internal Type System: Fast Object Types var p1; p1.north = 1; p1.south = 0; var p2; p2.south = 0; p2.north = 1; north 1 south 0 north 1 south 0 north 1 south 0 Base Type “{}” Type “{north}” Type “{south}” Base Type “{}” Type “{south, north}”Type “{north, south}”
  • 20. Create fast types and avoid type mismatches Don’t add properties conditionally function Player(direction) { if (direction = “NE”) { this.n = 1; this.e = 1; } else if (direction = “ES”) { this.e = 1; this.s = 1; } ... } var p1 = new Player(“NE”); // p1 type {n,e} var p2 = new Player(“ES”); // p2 type {e,s} function Player(north,east,south,west) { this.n = north; this.e = east; this.s = south; this.w = west; } var p1 = new Player(1,1,0,0);//p1 type {n,e,s,w} var p2 = new Player(0,0,1,1);//p2 type {n,e,s,w} p1.type != p2.type p1.type == p2.type
  • 21. Avoid conversion from fast type to slower property bags Deleting properties forces conversion function Player(north,east,south,west) { this.n = north; this.e = east; this.s = south; this.w = west; } var p1 = new Player(); delete p1.n; function Player(north,east,south,west) { this.n = north; this.e = east; this.s = south; this.w = west; } var p1 = new Player(); p1.n = 0; // or undefined SLOW FAST
  • 22. Avoid creating slower property bags Restrict using getters, setters and property descriptors in perf critical paths function Player(north, east, south, west) { Object.defineProperty(this, "n", { get : function() { return nVal; }, set : function(value) { nVal=value; }, enumerable: true, configurable: true }); Object.defineProperty(this, "e", { get : function() { return eVal; }, set : function(value) { eVal=value; }, enumerable: true, configurable: true }); ... } var p = new Player(1,1,0,0); var n = p.n; p.n = 0; ... function Player(north, east, south, west) { this.n = north; this.e = east; this.s = south; this.w = west; ... } var p = new Player(1,1,0,0); var n = p.n; p.n = 0; ... SLOW FAST
  • 23. demo
  • 24. Results • Time in script execution reduced ~30% • Raw JS performance improved ~30% 3.8s 2.2s
  • 25. Best practices for fast objects and manipulations • Create and use fast types • Keep shapes of objects consistent • Avoid type mismatches for fast types
  • 26.
  • 27. Numbers in JavaScript • All numbers are IEEE 64-bit floating point numbers - Great for flexibility - Performance and optimization challenge 31bits 31-bit (tagged) Integers 1bit 1 31bits Object pointer 1bit 0 32bits 32bits Floats 32-bit Integers STACK HEAP FIXED LENGTH, FASTER ACCESS VARIABLE LENGTH, SLOWER ACCESS Boxed
  • 28. Avoid creating floats if they are not needed Fastest way to indicate integer math is |0 var r = 0; function doMath(){ var a = 5; var b = 2; r = ((a + b) / 2) |0 ; // r = 3 r = Math.round((a + b) / 2); // r = 4 } var r = 0; function doMath(){ var a = 5; var b = 2; r = ((a + b) / 2); // r = 3.5 } ... var intR = Math.floor(r); 0x005e4148r: 0x00000007r: 0x00000009r: Number 3.5 STACK HEAP STACK SLOW FAST SLOW
  • 29. Take advantage of type-specialization for arithmetic Create separate functions for ints and floats; use consistent argument types function Distance(p1, p2) { var dx = p1.x - p2.x; var dy = p1.y - p2.y; var d2 = dx * dx + dy * dy; return Math.sqrt(d2); } var point1 = {x:10, y:10}; var point2 = {x:20, y:20}; var point3 = {x:1.5, y:1.5}; var point4 = {x:0x0AB, y:0xBC}; Distance(point1, point3); Distance(point2, point4); function DistanceFloat(p1, p2) { var dx = p1.x - p2.x; var dy = p1.y - p2.y; var d2 = dx * dx + dy * dy; return Math.sqrt(d2); } function DistanceInt(p1,p2) { var dx = p1.x - p2.x; var dy = p1.y - p2.y; var d2 = dx * dx + dy * dy; return (Math.sqrt(d2) | 0); } var point1 = {x:10, y:10}; var point2 = {x:20, y:20}; var point3 = {x:1.5, y:1.5}; var point4 = {x:0x0AB, y:0xBC}; DistanceInt(point1, point2); DistanceFloat(point3, point4); SLOW FAST
  • 30. Best practices for fast arithmetic • Use 31-bit integer math when possible • Avoid floats if they are not needed • Design for type specialized arithmetic
  • 31.
  • 32. Pre-allocate arrays var a = new Array(100); for (var i = 0; i < 100; i++) { a[i] = i + 2; } var a = new Array(); for (var i = 0; i < 100; i++) { a.push(i + 2); } 0 ? ?+1 ?? …0 100 SLOW FAST
  • 33. var a = new Array(100000); for (var i = 0; i < a.length; i++) { a[i] = i; } ... //operations on the array ... a[99] = “str”; For mixed arrays, provide an early hint Avoid delayed type conversion and copy var a = new Array(100000); a[0] = “hint”; for (var i = 0; i < a.length; i++) { a[i] = i; } ... //operations on the array ... a[99] = “str”; SLOW FAST
  • 34. Keep values in arrays consistent Numeric arrays treated like Typed Arrays internally var a = [1,0x2,99.1,5]; //mixed array var b = [0x10,8,9]; //mixed array function add(a,i,b,j) { return a[i] + b[j]; } add(a,0,b,0); add(a,1,b,1); var a = [1,5,8,9]; //int array var b = [0x02,0x10,99.1]; //float array function add(a,i,b,j) { return a[i] + b[j]; } add(a,0,b,0); add(a,1,b,1); SLOW FAST
  • 35. Keep arrays dense Deleting elements can force type change and de-optimization var a = new Array(1000); //type int ... for (var i = 0; i < boardSize; i++) { matrix[i] = [1,1,0,0]; } //operating on the array ... delete matrix[23]; ... //operating on the array var a = new Array(1000); //type int ... for (var i = 0; i < boardSize; i++) { matrix[i] = [1,1,0,0]; } //operating on the array ... matrix[23] = 0; ... //operating on the array SLOW FAST
  • 36. Enumerate arrays efficiently Explicit caching of length avoids repetitive property accesses var a = new Array(100); var total = 0; for (var item in a) { total += item; }; a.forEach(function(item){ total += item; }); for (var i = 0; i < a.length; i++) { total += a[i]; } var a = new Array(100); var total = 0; cachedLength = a.length; for (var i = 0; i < cachedLength; i++) { total += a[i]; } SLOW FAST
  • 37. Best practices for using arrays efficiently • Pre-allocate arrays • Keep array type consistent • Use typed arrays when possible • Keep arrays dense • Enumerate arrays efficiently
  • 38.
  • 39. Avoid chattiness with the DOM ... //for each rotation document.body.game.getElementById(elID).classList.remove(oldClass) document.body.game.getElementById(elID).classList.add(newClass) ... var element = document.getElementById(elID).classList; //for each rotation element.remove(oldClass) element.add(newClass) ... JavaScript DOM JavaScript DOM
  • 40. Avoid automatic conversions of DOM values Values from DOM are strings by default this.boardSize = document.getElementById("benchmarkBox").value; for (var i = 0; i < this.boardSize; i++) { //this.boardSize is “25” for (var j = 0; j < this.boardSize; j++) { //this.boardSize is “25” ... } } this.boardSize = parseInt(document.getElementById("benchmarkBox").value); for (var i = 0; i < this.boardSize; i++) { //this.boardSize is 25 for (var j = 0; j < this.boardSize; j++) { //this.boardSize is 25 ... } } FAST (25% marshalling cost reduction in init function) SLOW
  • 41. Paint as much as your users can see Align timers to display frames setInterval(animate, 0); setTimeout(animate, 0); requestAnimationFrame(animate); setInterval(animate, 1000 / 60); setTimeout(animate, 1000 / 60); MORE WORK LESS WORK
  • 42. demo
  • 43. Results Save CPU cycles 75% 65% setTimeout(animate, 0); requestAnimationFrame(animate);
  • 44. Optimized JS code: http://aka.ms/FasterJS
  • 45.
  • 46.
  • 47. Overview Concepts High Performance Websites Steve Souders, September 2007 Event Faster Websites: Best Practices Steve Souders, June 2009 High Performance Browser Networking Ilya Grigorik, September 2013 JavaScript Patterns High Performance JavaScript Nicholas Zakas, March 2010 JavaScript the Good Parts Douglas Crockford, May 2008 JavaScript Patterns Stoyan Stefanov, September 2010 JavaScript Cookbook Shelley Powers, July 2010 Microsoft Guidance Windows Store App: JavaScript Best Practices MSDN, December 2012 Performance Tricks to Make Apps & Sites Faster Jatinder Mann, Build 2012 50 Performance Tricks for Windows Store Apps Jason Weber, Build 2011 Engineering Excellence Performance Guidance Jason Weber, EE Forum 2011 Internet Explorer Architectural Overview Jason Weber, PDC 2011 W3C Web Performance Web Performance Working Group Homepage Navigation Timing Specification Blog Posts 1) Measuring Performance with ETW/XPerf 2) Measuring Performance in Lab Environments 3) Browser Subsystems Overview 4) What Common Benchmarks Measure Tools Windows Performance Toolkit Fiddler Web Debugger Contact Doris Chen Twitter: @doristchen Email: doris.chen@Microsoft.com
  • 49. PAGE • Responsive Web Design and CSS3 • http://bit.ly/CSS3Intro • HTML5, CSS3 Free 1 Day Training • http://bit.ly/HTML5DevCampDownload • Using Blend to Design HTML5 Windows 8 Application (Part II): Style, Layout and Grid • http://bit.ly/HTML5onBlend2 • Using Blend to Design HTML5 Windows 8 Application (Part III): Style Game Board, Cards, Support Different Device, View States • http://bit.ly/HTML5onBlend3 • Feature-specific demos • http://ie.microsoft.com/testdrive/ • Real-world demos • http://www.beautyoftheweb.com/
  • 50. Microsoft BizSpark Software • Three year access to current, full-featured software development tools • $150 of monthly Windows Azure benefits and discounted rates to quickly build, deploy and manage web applications • Professional technical and product support • Unique and valuable offers from the BizSpark Network Partners to help run your business • Four free MSDN Support Incidents. • Profile, Offers and Events • A connection to the BizSpark ecosystem, giving startups access to investors, advisors and mentors • Opportunities to achieve marketing visibility Support Visibility Microsoft BizSpark is a global program that provides free software, support and visibility to help startups succeed. There are 50K startups in BizSpark in 100+ countries. The three year program is free of charge and gives startups: