How to write up to 98% faster JavaScript code.

JavaScript performance comparison

Revision 14 of this test case created

Info

This test shows that frameworks built on a global namespace (jQuery, YUI, Prototype, ...) could have been up to 98% faster (Firefox) if they were written in a string based modular fashion like it is used by Compact.js that is based on Require.js

Please tell me wrong, I can't believe it :-) Dominik Guzei Wizzart

Preparation code

<script>
  (function() {
   var f = {},
       g = Array.prototype.slice;
   window.define = function() {
    var a = arguments,
        d = a[0],
        b = null;
    a = g.call(a, 1);
    if (a.length > 1) {
     b = a[0];
     for (var c = [], e = 0; e < b.length; e++) c[e] = f[b[e]];
     b = a[1].apply(this, c)
    } else b = a[0]();
    f[d] = b
   };
   window.require = function() {
    var a = arguments,
        d = [],
        b = null;
    a.length > 2 && (a = g.call(a, 1));
    d = a[0];
    b = a[1];
    a = [];
    for (var c = 0; c < d.length; c++) a[c] = f[d[c]];
    b.apply(this, a)
   }
  })();
 
 
  var Library2 = {
   util: {
    add: function(a, b) {
     return a + b;
    }
   },
 
   cool: {
    Class: function(startValue) {
     this.value = startValue;
    }
   }
  };
 
  var Library2utiladd = Library2.util.add;
 
  Library2.cool.Class.prototype.addToValue = function(value) {
   this.value = Library2utiladd(this.value, value);
  };
 
 
  define('Library.util.add', function() {
   return function(a, b) {
    return a + b;
   }
  });
 
  define('Library.cool.Class', ['Library.util.add'], function(add) {
 
   var Class = function(startValue) {
    this.value = startValue;
   };
 
   Class.prototype.addToValue = function(value) {
    this.value = add(this.value, value);
   };
 
   return Class;
 
  });
 
  var Library2coolClass = window.Library2.cool.Class;
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Global namespace chain
var instance = new Library2coolClass(1);

while (instance.value < 100000) {
 instance.addToValue(1);
}
pending…
Local string based modules
require(['Library.cool.Class'], function(Class) {
 var instance = new Class(1);

 while (instance.value < 100000) {
  instance.addToValue(1);
 }
});
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment