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

Mathias Bynens
Mathias BynensFreelance front-end developer at Qiwi
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
1 of 74

Recommended

The Beauty Of Java Script V5a by
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
899 views77 slides
The Beauty of Java Script by
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java ScriptMichael Girouard
22.7K views79 slides
Javascript - The Good, the Bad and the Ugly by
Javascript - The Good, the Bad and the UglyJavascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the UglyThorsten Suckow-Homberg
3.7K views68 slides
Node.js for PHP developers by
Node.js for PHP developersNode.js for PHP developers
Node.js for PHP developersAndrew Eddie
2.9K views36 slides
5 Tips for Better JavaScript by
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
72.5K views57 slides
JavaScript ES6 by
JavaScript ES6JavaScript ES6
JavaScript ES6Leo Hernandez
1.4K views23 slides

More Related Content

What's hot

Javascript tid-bits by
Javascript tid-bitsJavascript tid-bits
Javascript tid-bitsDavid Atchley
2.3K views35 slides
Advanced JavaScript by
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptMahmoud Tolba
2.1K views40 slides
JavaScript Promise by
JavaScript PromiseJavaScript Promise
JavaScript PromiseJoseph Chiang
4.3K views28 slides
Adding ES6 to Your Developer Toolbox by
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxJeff Strauss
541 views124 slides
ES6 is Nigh by
ES6 is NighES6 is Nigh
ES6 is NighDomenic Denicola
8K views56 slides
meet.js - QooXDoo by
meet.js - QooXDoomeet.js - QooXDoo
meet.js - QooXDooRadek Benkel
1.7K views66 slides

What's hot(20)

Adding ES6 to Your Developer Toolbox by Jeff Strauss
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss541 views
meet.js - QooXDoo by Radek Benkel
meet.js - QooXDoomeet.js - QooXDoo
meet.js - QooXDoo
Radek Benkel1.7K views
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I... by ZFConf Conference
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference1.7K views
The promise of asynchronous PHP by Wim Godden
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
Wim Godden16.4K views
Writing Your App Swiftly by Sommer Panage
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App Swiftly
Sommer Panage2.3K views
Minimizing Decision Fatigue to Improve Team Productivity by Derek Lee Boire
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee Boire1.9K views
¿Cómo de sexy puede hacer Backbone mi código? by jaespinmora
¿Cómo de sexy puede hacer Backbone mi código?¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
jaespinmora618 views
JavaScript - Like a Box of Chocolates - jsDay by Robert Nyman
JavaScript - Like a Box of Chocolates - jsDayJavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
Robert Nyman10.1K views
Interceptors: Into the Core of Pedestal by Kent Ohashi
Interceptors: Into the Core of PedestalInterceptors: Into the Core of Pedestal
Interceptors: Into the Core of Pedestal
Kent Ohashi1.5K views
Symfony2 Service Container: Inject me, my friend by Kirill Chebunin
Symfony2 Service Container: Inject me, my friendSymfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friend
Kirill Chebunin8.2K views
Converting your JS library to a jQuery plugin by thehoagie
Converting your JS library to a jQuery pluginConverting your JS library to a jQuery plugin
Converting your JS library to a jQuery plugin
thehoagie1.9K views
Javascript essential-pattern by 偉格 高
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
偉格 高1.8K views

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

jQuery: out with the old, in with the new by
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the newRemy Sharp
1.3K views62 slides
Trimming The Cruft by
Trimming The CruftTrimming The Cruft
Trimming The CruftPeter Higgins
653 views49 slides
dojo.Patterns by
dojo.Patternsdojo.Patterns
dojo.PatternsPeter Higgins
5.4K views65 slides
Orlando BarCamp Why Javascript Doesn't Suck by
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suckerockendude
1.3K views12 slides
JavaScript Literacy by
JavaScript LiteracyJavaScript Literacy
JavaScript LiteracyDavid Jacobs
976 views12 slides
JavaScript Primer by
JavaScript PrimerJavaScript Primer
JavaScript PrimerDaniel Cousineau
1.7K views82 slides

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

jQuery: out with the old, in with the new by Remy Sharp
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
Remy Sharp1.3K views
Orlando BarCamp Why Javascript Doesn't Suck by erockendude
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude1.3K views
Sane Async Patterns by TrevorBurnham
Sane Async PatternsSane Async Patterns
Sane Async Patterns
TrevorBurnham14.6K views
Why I Love JSX! by Jay Phelps
Why I Love JSX!Why I Love JSX!
Why I Love JSX!
Jay Phelps896 views
Symfony CMF - PHP Conference Brazil 2011 by Jacopo Romei
Symfony CMF - PHP Conference Brazil 2011Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011
Jacopo Romei2.9K views
Jquery Best Practices by brinsknaps
Jquery Best PracticesJquery Best Practices
Jquery Best Practices
brinsknaps3.4K views
Matthew Eernisse, NodeJs, .toster {webdev} by .toster
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster1.4K views
Java & Script ─ 清羽 by taobao.com
Java & Script ─ 清羽Java & Script ─ 清羽
Java & Script ─ 清羽
taobao.com372 views
Building High Performance Web Applications and Sites by goodfriday
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
goodfriday451 views

Recently uploaded

Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...ShapeBlue
55 views12 slides
Five Things You SHOULD Know About Postman by
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About PostmanPostman
38 views43 slides
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesShapeBlue
84 views15 slides
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...ShapeBlue
26 views29 slides
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...ShapeBlue
37 views15 slides
Microsoft Power Platform.pptx by
Microsoft Power Platform.pptxMicrosoft Power Platform.pptx
Microsoft Power Platform.pptxUni Systems S.M.S.A.
61 views38 slides

Recently uploaded(20)

Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ... by ShapeBlue
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
Backup and Disaster Recovery with CloudStack and StorPool - Workshop - Venko ...
ShapeBlue55 views
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman38 views
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue84 views
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue26 views
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R... by ShapeBlue
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
Setting Up Your First CloudStack Environment with Beginners Challenges - MD R...
ShapeBlue37 views
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
ShapeBlue26 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker48 views
State of the Union - Rohit Yadav - Apache CloudStack by ShapeBlue
State of the Union - Rohit Yadav - Apache CloudStackState of the Union - Rohit Yadav - Apache CloudStack
State of the Union - Rohit Yadav - Apache CloudStack
ShapeBlue106 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc72 views
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn26 views
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT by ShapeBlue
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
ShapeBlue66 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue54 views
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... by ShapeBlue
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
ShapeBlue64 views
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue28 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue44 views

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