SlideShare a Scribd company logo
Performance Patterns




Stoyan Stefanov
JSConfEU
Berlin, 2010
http://slideshare.net/stoyan/
About me
           YSlow 2.0
Lies,
      damn lies,
and performance advise
On the agenda
1.  Understanding the problem
2.  Some pointers/patterns
Moving targets
Performance patterns
Moving targets
•  Browsers
•  Libraries


•  e.g. IE string concatenation
+= or array.join()
var res = '',	        var res = [],	
    count = 10000;	       count = 10000;	
while (count--) {	    while (count--) {	
 res += 'a';	          res.push('a');	
}	                    }	

                      res = res.join('');	



              http://jsperf.com/join-concat/
“The Pen is mightier
       than the Sword” *

* only if the Sword is very small
   and the Pen very sharp
Benchmarks
Commonly…
var start = new Date();	
// ... go crazy ...	
var took = new Date() – start;
But…
•  Releasing the thread?
•  Updating the page?
•  In-memory DOM
  operations?
Better…
var start = new Date();	
// ... go crazy ...	
setTimeout(function () {	
    var took = new Date() – start;   	
}, 0);
Zero timeout
•  15 ms in IE
•  10 in FF, Safari
•  4 in Chrome
When benchmarking…
1.  Long enough operations
    (much longer than 15ms)
2.  200 runs for statistical
    significance
3.  Filtering outliers
4.  0-timeout end time
Results
•  Average
•  Median
•  Throw < 25% and >75%
Quarters


   ¼       ¼          ¼    ¼

 Garbage       Data       Garbage
Benchmarks
•  No need to benchmark
   browsers
•  Time values not important
•  Question is: given A and B,
   which way to go? Really?
   All the time?
JSPerf.com
•  Type in a form
•  Test, compare browsers
•  Community
Performance patterns
How about real life?
Performance patterns
Performance patterns
Performance patterns
Performance patterns
Picking the battles
Speeding Up
Speeding Up
1.  Loading
2.  Running
Speeding Up
1.  Loading
2.  Running
Loading – the basics
•  Reducing the # scripts
•  Gzip
•  Minification
•  Expires
•  CDN
Loading asynchronously
•  Async === Good
•  Progress
•  Perception
JavaScript blocks



   html
          js
               png

               png
JavaScript at the bottom



   html
          png

          png

                js
Non-blocking JavaScript
•  defer and async	
•  Defer: IE innovation, ok to
   delay, but keep order
•  Async: HTML5, whatever
<script async src="my.js" onload="doIt()"></script> 
<script defer src="my.js" onload="doIt()"></script> 
defer and async timeline

               async
                   	


     defer
         	



         DOMContentLoaded
                        	   load
Non-blocking JavaScript
•    Asynchronous JavaScript
     html
                  js

            png

            png


var js = document.createElement('script'); 
js.src = 'myscript.js'; 
var h = document.getElementsByTagName('head')[0]; 
h.appendChild(js); 
flush() early
 html
                         png

                    js               
                               css



 html



   js
        png
                                     ✔
              css
flush()
<html>	
<head>	
  <script src="my.js" 	
   	type="text/javascript"></script>	
  <link href="my.css" 	
   	type="text/css" rel="stylesheet" />	
</head>	

<?php flush() ?>
<body>	
  ....
Progressive rendering
                         Chunk
                         #1




                         Chunk
                         #2




x.appendChild(script)	   Chunk
                         #3
<!doctype html>	
<html>	
<head><title>My App</title></head>	
<body>	
  <div id="header">	
     <img src="logo.png" />	
     ...	
  </div>                   <!-- end of chunk #1 -->	

  ... The full body of the page ...	
                           <!-- end of chunk #2 -->	



<script src="all_20100925.js"></script>	
</body>	
</html>                    <!-- end of chunk #3 -->
Script injection patterns
document.getElementsByTagName("head")[0]	
    .appendChild(script);	

document.documentElement.firstChild	
   	.appendChild(script);	

document.body.appendChild(script);	

var first_script = document	
    .getElementsByTagName('script')[0];	
first_script.parentNode	
    .insertBefore(script, first_script);
HTTP chunking: not only HTML
HTTP chunking: not only HTML
•  Google Instant
•  /*""*/ - delimited JSON
   pieces, MXHR anyone?
•  Chunk #1 suggestions
•  Chunk #2 results

                    http://tinyurl.com/chunkview
Moar HTML5 attributes
•    ping="http://stats…"	
•    prefetch="http://later…"
Preload sans execute
var preload; 	
if (/*@cc_on!@*/false) { // IE 	
    preload = function (file) {	
        new Image().src = file;	
    };	
} else {	
    preload = function (file) {	
        var obj = document.createElement('object'),	
            body = document.body;	
        obj.width = 0;	
        obj.height = 0;	
        obj.data = file;	
        body.appendChild(obj);	
    };	
}
Speeding Up
1.  Loading
2.  Running
Runtime performance
1.  Going local
2.  Reusing
       aka caching, aka DRY
Runtime performance
1.  Going local
2.  Reusing
Local variables

•  globals are all sorts of bad
•  use var 
•  localize globals
Local variables
var a = 1; 	
(function (){	
  var a = 2; 	
  function b(){	
     var a = 3; 	
     alert(a);	
  }	
  b(); 	
})(); // 3
Local variables
var a = 1; 	
(function (){	
  var a = 2; 	
  function b(){	
     // var a = 3; 	
     alert(a);	
  }	
  b(); 	
})(); // 2
Local variables
var a = 1; 	
(function (){	
  // var a = 2; 	
  function b(){	
     // var a = 3; 	
     alert(a);	
  }	
  b(); 	
})(); // 1
Local variables

•  less crawling up the scope
chain
•  helps minification
Localization
var mamodule = (function () {	

  window...	
  document...	
  otherModule...   	

}());
Localization
var mamodule = (function (g, d, om)
{	

  g... // global	
  d... // document reference	
  om... // another common module	

}(this, document, otherModule));
Runtime performance
1.  Going local
2.  Reusing, aka caching
Init-time branching
•  Before… 
function myEvent(el, type, fn) {	
     if (window.addEventListener) {	
       el.addEventListener(type, fn, false);	
  } else if (window.attachEvent) {	
       el.attachEvent("on" + type, fn);	
  } else {...	
}
Init-time branching
•  After… 
if (window.addEventListener) {	
     var myEvent = function (el, type, fn) {	
       el.addEventListener(type, fn, false);	
  }	
} else if (window.attachEvent) {	
  var myEvent = function (el, type, fn) {	
       el.attachEvent("on" + type, fn);	
  }	
}
Memoization
•  for expensive, repeating tasks

function myFunc(param){	
    if (!myFunc.cache) {	
        myFunc.cache = {};	
    }	
    if (!myFunc.cache[param]) {	
        var result = {}; // ...	
        myFunc.cache[param] = result;	
    }	
    return myFunc.cache[param];	
}
Memoization – other options
•  in a closure
•  offline
Classical       inheritance
•  Before…

var inherit = function (C, P) {	
  var F = function () {};	
  F.prototype = P.prototype;	
  C.prototype = new F();	
  C.uber = P.prototype;	
  C.prototype.constructor = C;	
};
Classical        inheritance
•  After…

var inherit = (function () {	
  var F = function () {};	
  return function (C, P) {	
     F.prototype = P.prototype;	
     C.prototype = new F();	
     C.uber = P.prototype;	
     C.prototype.constructor = C;	
  }	
}());	
                 http://jsperf.com/holy-grail-classical-reuse
Regex loops
•  Before…

var i = 1000,	
    dude;	

while (i--) {	
    dude = /[a-z]/.test('duderino');	
};
Regex loops
•  After…

var i = 1000,	
    dude, 	
    re = /[a-z]/;	

while (i--) {	
    dude = re.test('duderino');	
}	



                          http://jsperf.com/regexp-loops
Cashing lengths in loops
•  before…

var a = [];	

for (var i = 0; i < a.length; i++) {	
    console.log(a[i]);	
}
Cashing lengths in loops
•  later…

var a = [], 	
    i = 0;	

for (; i < a.length; i += 1) {	
    console.log(a[i]);	
}
Cashing lengths in loops
•  after…

var a = [], 	
    i = 0,	
    len = a.length;	

for (; i < len; i += 1) {	
    console.log(a[i]);	
}
Cashing lengths in loops
•  alternatively…

var a = [], 	
   i = a.length;	

while (i--) {	
    console.log(a[i]);	
}
DOM
DOM – case A
// bad 	
var count = 0;	
for (; count < 15000; count += 1) {	

     document.getElementById('here').innerHTML += 'a'; 	

}	

// DOM access = (1 get + 1 set) * 15000
DOM – case B
// better	
var count = 0, content = ''; 	
for (; count < 15000; count += 1) {	

    content += 'a'; 	

}	
document.getElementById('here').innerHTML += content;	

// DOM access: get + set
IE 6


        IE 7


        IE 8


  Firefox 3


 Firefox 3.5


 Safari 3.2


   Safari 4


 Chrome 2


 Chrome 3


Opera 9.64
               How bad is A compared to B?




 Opera 10
ECMAland   DOMland
DOM is slow
Proxy Design Pattern
Proxy pattern
•  One object acts as an
  interface to another
Proxy pattern
Proxy pattern
Proxy pattern
Proxy pattern
Words of Wisdom
•  Ask why? How?
•  Load quickly and async
•  Don’t touch the DOM
•  Go local
Thank you!


Stoyan Stefanov
@stoyanstefanov
http://www.phpied.com

More Related Content

PDF
Introduction to Nodejs
PDF
Web Crawling with NodeJS
PDF
JavaScript & HTML5 - Brave New World
PDF
HTML5 JavaScript APIs
PDF
Node.js in action
ZIP
Javascript Everywhere
PDF
Forget the Web
PDF
Server Side JavaScript - You ain't seen nothing yet
Introduction to Nodejs
Web Crawling with NodeJS
JavaScript & HTML5 - Brave New World
HTML5 JavaScript APIs
Node.js in action
Javascript Everywhere
Forget the Web
Server Side JavaScript - You ain't seen nothing yet

What's hot (20)

PDF
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
PPTX
Building High Performance Web Applications and Sites
PPTX
ES6 is Nigh
PDF
From Node to Go
PDF
Testing Web Applications with GEB
PDF
Appsec usa2013 js_libinsecurity_stefanodipaola
PDF
JavaScript Promise
PDF
Apache CouchDB talk at Ontario GNU Linux Fest
PDF
Ajax Performance Tuning and Best Practices
ODP
The promise of asynchronous PHP
PDF
HTML5: where flash isn't needed anymore
PDF
Django Heresies
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PPTX
KISSY 的昨天、今天与明天
PDF
kissy-past-now-future
PDF
NoSQL & MongoDB
PDF
"The little big project. From zero to hero in two weeks with 3 front-end engi...
PDF
performance vamos dormir mais?
PDF
Testing Backbone applications with Jasmine
PDF
History of jQuery
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Building High Performance Web Applications and Sites
ES6 is Nigh
From Node to Go
Testing Web Applications with GEB
Appsec usa2013 js_libinsecurity_stefanodipaola
JavaScript Promise
Apache CouchDB talk at Ontario GNU Linux Fest
Ajax Performance Tuning and Best Practices
The promise of asynchronous PHP
HTML5: where flash isn't needed anymore
Django Heresies
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
KISSY 的昨天、今天与明天
kissy-past-now-future
NoSQL & MongoDB
"The little big project. From zero to hero in two weeks with 3 front-end engi...
performance vamos dormir mais?
Testing Backbone applications with Jasmine
History of jQuery
Ad

Similar to Performance patterns (20)

PPTX
JavaScript performance patterns
PPTX
JavaScript Performance Patterns
KEY
#NewMeetup Performance
PDF
Progressive Downloads and Rendering
PPTX
the next web now
PPTX
Progressive downloads and rendering (Stoyan Stefanov)
PDF
Lecture 03 - JQuery.pdf
PPTX
Make BDD great again
PDF
Performance Optimization and JavaScript Best Practices
PDF
Nodejs - A quick tour (v6)
PPT
Enhance Web Performance
PDF
Web Performance Workshop - Velocity London 2013
PDF
Node.js flow control
PPTX
Run Node Run
PPTX
introduction to node.js
PPTX
JS Essence
PDF
Unit Testing JavaScript Applications
PPTX
1-JAVA SCRIPT. servere-side applications vs client side applications
PPTX
Javascript first-class citizenery
PDF
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
JavaScript performance patterns
JavaScript Performance Patterns
#NewMeetup Performance
Progressive Downloads and Rendering
the next web now
Progressive downloads and rendering (Stoyan Stefanov)
Lecture 03 - JQuery.pdf
Make BDD great again
Performance Optimization and JavaScript Best Practices
Nodejs - A quick tour (v6)
Enhance Web Performance
Web Performance Workshop - Velocity London 2013
Node.js flow control
Run Node Run
introduction to node.js
JS Essence
Unit Testing JavaScript Applications
1-JAVA SCRIPT. servere-side applications vs client side applications
Javascript first-class citizenery
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Ad

More from Stoyan Stefanov (20)

PDF
Reactive JavaScript
PPTX
YSlow hacking
PPTX
Liking performance
PPTX
High Performance Social Plugins
PDF
Social Button BFFs
PPTX
JavaScript навсякъде
PPTX
JavaScript is everywhere
PDF
JavaScript shell scripting
PDF
JavaScript for PHP developers
PDF
WPO @ PubCon 2010
PDF
Progressive Downloads and Rendering - take #2
PDF
Voices that matter: High Performance Web Sites
PDF
Psychology of performance
PPT
3-in-1 YSlow
PDF
CSS and image optimization
PPT
High-performance DOM scripting
PPT
The business of performance
PDF
JavaScript Patterns
PDF
Ignite Velocity: Image Weight Loss Clinic
PDF
Don't make me wait! or Building High-Performance Web Applications
Reactive JavaScript
YSlow hacking
Liking performance
High Performance Social Plugins
Social Button BFFs
JavaScript навсякъде
JavaScript is everywhere
JavaScript shell scripting
JavaScript for PHP developers
WPO @ PubCon 2010
Progressive Downloads and Rendering - take #2
Voices that matter: High Performance Web Sites
Psychology of performance
3-in-1 YSlow
CSS and image optimization
High-performance DOM scripting
The business of performance
JavaScript Patterns
Ignite Velocity: Image Weight Loss Clinic
Don't make me wait! or Building High-Performance Web Applications

Recently uploaded (20)

PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Empathic Computing: Creating Shared Understanding
PDF
Modernizing your data center with Dell and AMD
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Chapter 3 Spatial Domain Image Processing.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation_ Review paper, used for researhc scholars
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Empathic Computing: Creating Shared Understanding
Modernizing your data center with Dell and AMD
NewMind AI Monthly Chronicles - July 2025
Electronic commerce courselecture one. Pdf
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Review of recent advances in non-invasive hemoglobin estimation
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
NewMind AI Weekly Chronicles - August'25 Week I
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Chapter 3 Spatial Domain Image Processing.pdf

Performance patterns