Cheat sheet: Tips for high performance JavaScript

Tips for high performance JavaScript

a set of tips on how to speed up your JavaScript.

reference:
based on the article The Simplest Thing Possible: Managing JavaScript Performance by John V. Petersen in CODE magazine. That article is good, but it is too long for day to day reference, and is missing some tips :) .  So, here is a quick cheat sheet of JavaScript performance tips:

Further Reading:
High Performance JavaScript by Nicholas Zakas
________________________________________________
tip: Use Local Variables
avoid '.' references, and instead use a local variable to cache the scope reference:

var doc = window.document;
//now use doc, instead of window.document
________________________________________________
tip: avoid repeated DOM lookups
var _jquery = $;
var elem = _jquery(_jquery('#elem1'));
//now use elem, instead of looking up '#elem1'
________________________________________________
tip: only use jQuery etc when necessary

//example: to lookup an element, you do not always need jQuery:
var elem = document.getElementById('#elem1');
________________________________________________
tip: CSS: use classes instead of inline styles
//instead of calling elem.hide(), use a CSS class:
.hidden {
  display: none
}

elem.className = 'hidden';
________________________________________________
tip: to reduce memory usage, instead of creating temp functions, you extend the prototype
function someClass() {
  var _privateColor = 'red';
};

//GetVersion() is not a temp function inside someClass(), but instead is a prototyped function:
someClass.prototype.GetVersion = function() {
  return 1.1;
};
________________________________________________
tip: instead of directly using HTML collections, you use arrays
var divElems = document.getElementsByTagName('div');
var divElemsArray = Array.prototype.concat.call(divElems); 
//TODO can we avoid the . referencing ?

//Now use the divElemsArray instead of divElems
________________________________________________
tip: cache reference to array item, instead of repeatedly looking up
var item = myArray[5];
//now use the cached item:
item.SetColor('blue');
item.SetHeight(200);
________________________________________________
tip: avoid creating unnecessary functions
var result = varOne + varTwo; //no need to create an Add() function !
________________________________________________
tip: avoid for in loop
for loops are ok
while loops are ok
do loops are ok
for in loops are slower and should be avoided (the JavaScript engine has to figure out which properties have the Enumerable attribute set to be true).  Instead, use a regular for loop to iterate over an array.

TODO: what about jQuery each() loops ?
TODO: what Array.prototype.forEach ?
________________________________________________
tip: take advantage of boolean expression short-cicuiting
In a boolean expression joined by AND operations, the first false sub-expression will cause the evaluation to complete early, saving time.
var result = isOk && expensiveOperation(); //expensiveOperation() is only called when isOk is true
________________________________________________
tip: avoid try catch, when possible (perhaps in Release build)
//global error handler, instead of try .. catch
window.onerror = function(msg, url, lineNumber) {
  //handle the error here
}
________________________________________________
tip: avoid with(), as it is slow
//instead of with(), just set the properties one at a time:
var myObj = someObject;
myObj.Color = 'red';
myObj.Speed = 10;
________________________________________________
tip: avoid temporary objects, including function objects
the JavaScript GC is timesliced, and so only has a tiny amount of time to do its work (typically about 10ms).  if you create lots of small objects, then the GC may not have enough time to catch up, and so even though your code is clearing up references OK, you will have a memory leak.

So, avoid creating too many temporary objects, including function objects.
________________________________________________
tip: to save memory and GC work, replace temporary function in loop, with a function reference
var calcArea = function(circle) {
  circle.Area = Math.PI * circle.radius * circle.radius;
};

//loop that uses a reference to the function:
circles.forEach(calcArea);
________________________________________________
tip: use 'self' not bind()
don't get your self in a bind: instead of using function.bind(), try instead using a local 'self' variable.

Square.prototype.AddEvents = function()
{
  var self = this;
  $("#myDiv").on("click",function(){
    var color = self.GetColor(); //using 'self' instead of bind(this)
    $("p").toggleClass("intro-" + color);
  });
};

benefits:
  • simpler code -> faster
  • no temporary function object created (compared to jQuery bind())
  • bind() can fail when running JavaScript using jsPhantom
    • this is important if you want your code to run as part of CI build via Chutzpah
________________________________________________

Comments