SlideShare a Scribd company logo
How DRY impacts JavaScript performance //
Faster JavaScript execution for the lazy developer
Mathias Bynens – Velocity Europe, November 2011
@mathias
JavaScript & performance




          Rule #1: nothing to do with JS
JavaScript & performance
JavaScript & performance



                  What about
        the actual run-time performance
              on the client side?
DRY
      flic.kr/p/2ZGCT
WET
      flic.kr/p/5Jnj7Q
“DRY leads to readable,
  maintainable code”
DRY JavaScript
  improves
 performance
     …if you do it right
So, where to avoid
    repetition?
What’s slow in JavaScript?
What’s slow in JavaScript?
1. The DOM
What’s slow in JavaScript?
1. The DOM

2. Function calls
What’s slow in JavaScript?
1. The DOM

2. Function calls

3. Lookups
DOM manipulation
// Create the element in memory
var el = document.createElement('p');


// Insert the element into the DOM
document.body.appendChild(el);
DOM manipulation
<body>
  …
  <div>
      <p></p>
  </div>
</body>
DOM manipulation
var div = document.createElement('div'),
    p = document.createElement('p');


// Bad
document.body.appendChild(div);
div.appendChild(p);
DOM manipulation
var div = document.createElement('div'),
    p = document.createElement('p');


// Better
div.appendChild(p);
document.body.appendChild(div);
DOM manipulation
<body>
  …
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</body>
DOM manipulation
var p = document.createElement('p'),

      i = 4;



while (i--) { // Add four <p> elements

    document.body.appendChild(p.cloneNode(false));

}
DOM manipulation
var frag = document.createDocumentFragment(),
      p = document.createElement('p'),
      i = 4;


while (i--) { // Add four <p> elements
    frag.appendChild(p.cloneNode(false));
}


document.body.appendChild(frag);
Function calls
// Function declaration

function foo(bar) {

    return bar;

}

// Function call

foo('something');
Function calls
alert('foo');
document.getElementById('foo');
$('#foo');
Function calls
$('.foo').show();
// other stuff…
$('.foo').hide();
Function calls
var $foo = $('.foo');
$foo.show();
// other stuff…
$foo.hide();
Function calls
var $foo = $('.foo').show();
// other stuff…
$foo.hide();
Property lookups
var obj = {
     'x': 42,
     'y': {
         'foo': 'bar'
     }
};


obj.x; // 42
obj.y.foo; // 'bar'
Property lookups
document.title

dojo.query(…)

YAHOO.util.Dom.get(…)
Property lookups
var foo = YAHOO.util.Dom.get('foo'),
    bar = YAHOO.util.Dom.get('bar'),
    baz = YAHOO.util.Dom.get('baz'),
    qux = YAHOO.util.Dom.get('qux');
Property lookups
var get = YAHOO.util.Dom.get,
    foo = get('foo'),
    bar = get('bar'),
    baz = get('baz'),
    qux = get('qux');
Array item lookups
var elems = document.getElementsByTagName('p'),
        length = elems.length;


while (length--) {
    if (elems[length].className == 'foo') {
        // do something with elems[length]
        elems[length].innerHTML = 'LOLWAT';
    }
}
Array item lookups
var elems = document.getElementsByTagName('p'),
    length = elems.length,
    elem;

while (length--) {
  elem = elems[length];
  if (elem.className == 'foo') {
    // do something with elem
    elem.innerHTML = 'LOLWAT';
  }
}
Scope lookups
var foo = 42;
foo; // no scope lookup
Scope lookups
var foo = 42;
(function() {
  foo; // one scope lookup
}());
// IIFE – see http://mths.be/iife
Scope lookups
var foo = 42;
(function() {
  (function() {
    foo; // two scope lookups
  }());
}());
Scope lookups
Scope lookups
var foo = 42;
(function(foo) {
  (function(foo) {
    foo; // ZOMG, no scope lookups!!1
  }(foo));
}(foo));
Scope lookups
Scope lookups
(function() {
  // every time you use `window`
  // or `document` here
  // that’s a scope lookup
}());
Scope lookups
(function() {
  var doc = document,
        win = window;
  // lookup once, then cache
}());
Scope lookups
(function(win, doc) {
  // use `win` and `doc` here
  // no scope lookups
  // no performance penalty!
}(this, document));
Recap: what’s slow in JavaScript?
Recap: what’s slow in JavaScript?
1. The DOM
Recap: what’s slow in JavaScript?
1. The DOM

2. Function calls
Recap: what’s slow in JavaScript?
1. The DOM

2. Function calls

3. Lookups
Especially when used inside…
Especially when used inside…
• Loops
Especially when used inside…
• Loops

• Intervals
Especially when used inside…
• Loops

• Intervals

• Handlers for events that fire frequently
It happens to the best!
// Don’t do this:
$(window).scroll(function() {
  $('.foo').something();
});
It happens to the best!
// Don’t do this:
$(window).scroll(function() {
  $('.foo').something();
});
It happens to the best!
// Don’t do this:
$(window).scroll(function() {
  $('.foo').something();
});




// See http://mths.be/azs
typeof performance != 'the whole story'
tips & tricks
   (not really)
New objects
var obj = new Object();
obj.x = 42;
obj.y = 'foo';
obj.z = false;
New objects
var obj = {
     'x': 42,
     'y': 'foo',
     'z': false
};
New arrays
var arr = new Array();
arr.push(42);
arr.push('foo');
arr.push(false);
New arrays
var arr = [
     42,
     'foo',
     false
];
Avoid switch
switch(foo) {
  case 'alpha':
    // do X
    break;
  case 'beta':
    // do Y
    break;
  default:
    // do Z
    break;
}
Avoid switch
var switchObj = {
     'alpha': function() {
       // do X
     },
     'beta': function() {
          // do Y
     },
     '_default': function() {
       // do Z
     }
};
(switchObj.hasOwnProperty(foo) && switchObj[foo] || switchObj._default)(args);
Don’t use jQuery for everything
$('.foo').click(function() {
  $(this).prop('id');
  // same as this, before jQuery 1.6:
  // $(this).attr('id');


  // also `href`, `checked`, `value`…
});
Don’t use jQuery for everything
$('.foo').click(function() {
  this.id;
  this.href;
  this.checked;
  this.value;
  // etc.
});
jQuery document ready
$(document).ready(function() {
  // teh coads
});
jQuery document ready
$().ready(function() {
  // heh
});
jQuery document ready
$.fn.ready(function() {
  // not pretty, but fastest solution
});
jQuery document ready
$(function() {
  // moar sexy, but slower
});
jQuery document ready
(function() {
    // move <script>s to the bottom
    // and just use an IIFE*
}());




// * unless you use .appendChild() / .innerHTML on document.documentElement or document.body: http://mths.be/ieoa
jQuery collection size
$('.foo').size(); // NO.
jQuery collection size
// jQuery source:
$.fn.size = function() {
     return this.length;
};


// …so, just use:
$('.foo').length;
Use context
$('#foo .bar').addClass('baz');
$('#foo .qux').hide();
$('#foo input').removeClass('wut');
Use context
var $foo = $('#foo');
$('.bar', $foo).addClass('baz');
$('.qux', $foo).hide();
$('input', $foo).removeClass('wut');
this.location = 'http://jsperf.com/'
http://jsperf.com/browse/mathias-bynens
Questions?
   @mathias
Ad

Recommended

The Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
The Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
Javascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the Ugly
Thorsten Suckow-Homberg
 
Node.js for PHP developers
Node.js for PHP developers
Andrew Eddie
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
JavaScript ES6
JavaScript ES6
Leo Hernandez
 
Effective ES6
Effective ES6
Teppei Sato
 
JavaScript - From Birth To Closure
JavaScript - From Birth To Closure
Robert Nyman
 
Javascript tid-bits
Javascript tid-bits
David Atchley
 
Advanced JavaScript
Advanced JavaScript
Mahmoud Tolba
 
JavaScript Promise
JavaScript Promise
Joseph Chiang
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss
 
ES6 is Nigh
ES6 is Nigh
Domenic Denicola
 
meet.js - QooXDoo
meet.js - QooXDoo
Radek Benkel
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
Es.next
Es.next
Ignacio Gil
 
The promise of asynchronous PHP
The promise of asynchronous PHP
Wim Godden
 
Introduction of ES2015
Introduction of ES2015
Nakajima Shigeru
 
Writing Your App Swiftly
Writing Your App Swiftly
Sommer Panage
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
jaespinmora
 
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
Robert Nyman
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of Pedestal
Kent Ohashi
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friend
Kirill Chebunin
 
Converting your JS library to a jQuery plugin
Converting your JS library to a jQuery plugin
thehoagie
 
Javascript essential-pattern
Javascript essential-pattern
偉格 高
 
this
this
偉格 高
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the new
Remy Sharp
 
Trimming The Cruft
Trimming The Cruft
Peter Higgins
 

More Related Content

What's hot (20)

Javascript tid-bits
Javascript tid-bits
David Atchley
 
Advanced JavaScript
Advanced JavaScript
Mahmoud Tolba
 
JavaScript Promise
JavaScript Promise
Joseph Chiang
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss
 
ES6 is Nigh
ES6 is Nigh
Domenic Denicola
 
meet.js - QooXDoo
meet.js - QooXDoo
Radek Benkel
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
Es.next
Es.next
Ignacio Gil
 
The promise of asynchronous PHP
The promise of asynchronous PHP
Wim Godden
 
Introduction of ES2015
Introduction of ES2015
Nakajima Shigeru
 
Writing Your App Swiftly
Writing Your App Swiftly
Sommer Panage
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
jaespinmora
 
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
Robert Nyman
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of Pedestal
Kent Ohashi
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friend
Kirill Chebunin
 
Converting your JS library to a jQuery plugin
Converting your JS library to a jQuery plugin
thehoagie
 
Javascript essential-pattern
Javascript essential-pattern
偉格 高
 
this
this
偉格 高
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
The promise of asynchronous PHP
The promise of asynchronous PHP
Wim Godden
 
Writing Your App Swiftly
Writing Your App Swiftly
Sommer Panage
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
jaespinmora
 
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
Robert Nyman
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of Pedestal
Kent Ohashi
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friend
Kirill Chebunin
 
Converting your JS library to a jQuery plugin
Converting your JS library to a jQuery plugin
thehoagie
 
Javascript essential-pattern
Javascript essential-pattern
偉格 高
 

Similar to How DRY impacts JavaScript performance // Faster JavaScript execution for the lazy developer (20)

jQuery: out with the old, in with the new
jQuery: out with the old, in with the new
Remy Sharp
 
Trimming The Cruft
Trimming The Cruft
Peter Higgins
 
dojo.Patterns
dojo.Patterns
Peter Higgins
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
JavaScript Literacy
JavaScript Literacy
David Jacobs
 
JavaScript Primer
JavaScript Primer
Daniel Cousineau
 
Sane Async Patterns
Sane Async Patterns
TrevorBurnham
 
Why I Love JSX!
Why I Love JSX!
Jay Phelps
 
New in php 7
New in php 7
Vic Metcalfe
 
Java script for web developer
Java script for web developer
Chalermpon Areepong
 
Txjs
Txjs
Peter Higgins
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
Constantin Titarenko
 
Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011
Jacopo Romei
 
DrupalCon jQuery
DrupalCon jQuery
Nathan Smith
 
Jquery Best Practices
Jquery Best Practices
brinsknaps
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Java & Script ─ 清羽
Java & Script ─ 清羽
taobao.com
 
Object oriented JavaScript
Object oriented JavaScript
Rafał Wesołowski
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
goodfriday
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the new
Remy Sharp
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
JavaScript Literacy
JavaScript Literacy
David Jacobs
 
Why I Love JSX!
Why I Love JSX!
Jay Phelps
 
Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011
Jacopo Romei
 
Jquery Best Practices
Jquery Best Practices
brinsknaps
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Java & Script ─ 清羽
Java & Script ─ 清羽
taobao.com
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
goodfriday
 
Ad

Recently uploaded (20)

FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Ad

How DRY impacts JavaScript performance // Faster JavaScript execution for the lazy developer