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

More Related Content

What's hot (20)

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

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

PPTX
JavaScript front end performance optimizations
Chris Love
 
PDF
Building a JavaScript Library
jeresig
 
PDF
fuser interface-development-using-jquery
Kostas Mavridis
 
PPTX
Jquery fundamentals
Salvatore Fazio
 
PPT
Web Performance Tips
Ravi Raj
 
PPTX
JavaScript Performance Patterns
Stoyan Stefanov
 
PPTX
The Real Story Behind JavaScript Performance on Mobile... Because Science!
Ryan J. Salva
 
PPTX
Javascript for web Programming creating and embedding with html
E.M.G.yadava womens college
 
KEY
User Interface Development with jQuery
colinbdclark
 
KEY
jQuery Anti-Patterns for Performance
András Kovács
 
PDF
Intro to jQuery @ Startup Institute
Rafael Gonzaque
 
KEY
Week 4 - jQuery + Ajax
baygross
 
PDF
Performance patterns
Stoyan Stefanov
 
KEY
jQuery Anti-Patterns for Performance & Compression
Paul Irish
 
PPT
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
PPT
Javascript Experiment
wgamboa
 
PPT
Introduction to jQuery
Andres Baravalle
 
PPTX
Java script performance tips
Shakti Shrestha
 
PDF
Fast mobile web apps
Ivano Malavolta
 
PPT
Javascript Primer
Adam Hepton
 
JavaScript front end performance optimizations
Chris Love
 
Building a JavaScript Library
jeresig
 
fuser interface-development-using-jquery
Kostas Mavridis
 
Jquery fundamentals
Salvatore Fazio
 
Web Performance Tips
Ravi Raj
 
JavaScript Performance Patterns
Stoyan Stefanov
 
The Real Story Behind JavaScript Performance on Mobile... Because Science!
Ryan J. Salva
 
Javascript for web Programming creating and embedding with html
E.M.G.yadava womens college
 
User Interface Development with jQuery
colinbdclark
 
jQuery Anti-Patterns for Performance
András Kovács
 
Intro to jQuery @ Startup Institute
Rafael Gonzaque
 
Week 4 - jQuery + Ajax
baygross
 
Performance patterns
Stoyan Stefanov
 
jQuery Anti-Patterns for Performance & Compression
Paul Irish
 
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
Javascript Experiment
wgamboa
 
Introduction to jQuery
Andres Baravalle
 
Java script performance tips
Shakti Shrestha
 
Fast mobile web apps
Ivano Malavolta
 
Javascript Primer
Adam Hepton
 
Ad

Recently uploaded (20)

PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Linux schedulers for fun and profit with SchedKit
Alessio Biancalana
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
PPTX
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PPTX
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Evolution: How True AI is Redefining Safety in Industry 4.0
vikaassingh4433
 
PDF
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Linux schedulers for fun and profit with SchedKit
Alessio Biancalana
 
Digital Circuits, important subject in CS
contactparinay1
 
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Evolution: How True AI is Redefining Safety in Industry 4.0
vikaassingh4433
 
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
Ad

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