trevmex's tumblings

JavaScripter, Rubyist, Functional Programmer, Agile Practitioner.

jQuery’s $.extend is slow

I look at a lot of JavaScript code and I often run across something like this:

var TrevNS = {};
TrevNS.RockinClass = {/* other stuff ... */};
$.extend(TrevNS.RockinClass, {
    rock: function(str) {
        return("this " + str + " rocks!");
    },
    roll: function(str) {
        return("this " + str + " rolls!");
    }
});

Whenever I see some code like this I have to wonder why the author chose jQuery's $.extend instead of another method.

There are at least three other ways of writing this same code:

  1. Creating a function in the global namespace:
    var TrevNS = {};
    TrevNS.RockinClass = {/* other stuff ... */};
    function rock(str) {
        return("this " + str + " rocks!");
    }
    function roll(str) {
        return("this " + str + " rolls!");
    }
    TrevNS.RockinClass.rock = rock;
    TrevNS.RockinClass.roll = roll;
  2. Assigning methods as anonymous functions:
    var TrevNS = {};
    TrevNS.RockinClass = {/* other stuff ... */};
    TrevNS.RockinClass.rock = function (str) {
        return("this " + str + " rocks!");
    };
    TrevNS.RockinClass.roll = function (str) {
        return("this " + str + " rolls!");
    };
  3. Extending the class with prototype:
    var TrevNS = {};
    TrevNS.RockinSuperClass = function () {/* other stuff ... */};
    TrevNS.RockinSuperClass.prototype.rock = function (str) {
        return("this " + str + " rocks!");
    };
    TrevNS.RockinSuperClass.prototype.roll = function (str) {
        return("this " + str + " rolls!");
    };
    TrevNS.RockinClass = new TrevNS.RockinSuperClass();

So, I went online to see if there were any comparisons out there, and lo and behold, there were!

I discovered a great test at JSPerf.com. Here are my results from running the test on many browsers (all numbers are in operations/second):

This shows the following:

  1. $.extend is by far the slowest way to add functions to an object.
  2. Assigning methods as anonymous functions (var bar = function ()) is the fastest overall.
  3. Creating a function in the global namespace (function foo()) is sometimes faster, but sometimes the slowest (depending on the browser).

Judging from these results, it seems that the best way to extend your classes (i.e. objects) is by assigning them as anonymous functions.

That isn’t to say that $.extend has other good uses, such as extending multiple objects at once and deep copying, but for simply adding methods to an object, it isn’t the best solution.

Thanks to Jens Roland for making the test and Mathias Bynens for making JSPref.com!

(As a side note, Chrome on Mac OS X is the fastest of the browsers I tested, and IE 8 on Windows 7 was the slowest. The difference was HUGE!)

Notes

  1. sitaggart reblogged this from trevmex
  2. trevmex posted this