How to write up to 98% faster JavaScript code.

JavaScript performance comparison

Revision 9 of this test case created by eric

Info

This test shows that if you are not a JavaScript Ninja your framework code could have been up to 98% faster (Firefox) as when it was written in a string based modular fashion like it is used by Compact.js that is based on Require.js

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)
   }
  })();
</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
window.Library = {};
window.Library.util = {};
var add = window.Library.util.add = function(a, b) {
 return a + b
};
window.Library.cool = {};
window.Library.cool.Class = function(a) {
 this.value = a
};
window.Library.cool.Class.prototype.addToValue = function(a) {
 this.value = add(this.value, a)
};
for (var instance = new window.Library.cool.Class(1); instance.value < 1E5;) instance.addToValue(1);
pending…
Local string based modules
define("Library.util.add", function() {
 return function(a, b) {
  return a + b
 }
});
define("Library.cool.Class", ["Library.util.add"], function(a) {
 var b = function(a) {
  this.value = a
 };
 b.prototype.addToValue = function(b) {
  this.value = a(this.value, b)
 };
 return b
});
require(["Library.cool.Class"], function(a) {
 for (a = new a(1); a.value < 1E5;) a.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