Delegate Object Test

JavaScript performance comparison

Revision 3 of this test case created by James Wilkins

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var d = (function() {
   
      function Delegate(obj, func) {
        this.obj = obj;
        this.func = func;
        this.functext = func.toString();
        this.bindinvoke = func.bind(obj);
        var _this = obj; // (note: putting this in 'eval()' will slow it down!)
        this.evalinvoke = obj.constructor.prototype['test'] = eval("(" + func + ")");
        obj.constructor.prototype[this.functext] = this.evalinvoke;
      }
      var cases = "",
        argtext = "";
      for (var i = 0; i < 10; ++i)
        cases += "    case " + (1 + i) + ": return _this.func(this.obj, " + (argtext += "args[" + i + "], ") + "this);\r\n";
      var applyStr = (function(args) {
        var _this = this;
        if (args === void 0 || !args.length) return _this.evalinvoke(this.obj, this);
        switch (args.length) {
          case 1:
            return _this.func(this.obj, args[0], this);
            /*      case 2:
            return _this.func(this.obj, args[0], args[1], this);
          case 3:
            return _this.func.call(this, this.obj, args[0], args[1], args[2], this);*/

          default:
            return _this.func.apply(this.obj, [this.obj].concat(args, this));
        }
      }).toString().replace(/^.*case 1:[^;]*;/m, cases);
      Delegate.prototype.apply = eval("(" + applyStr + ")");
      Delegate.prototype.indirectApply = function(args) {
        return this.apply(args);
      }
      var o = {
        x: 1
      };
      var d = new Delegate(o, function test(_this) {
        return (typeof _this != 'undefined') ? _this.x : this.x;
      });
   
      return d;
    })();
};
</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
bind invoke
d.bindinvoke();
pending…
eval invoke
d.evalinvoke();
pending…
direct on object
d.obj.test();
pending…
direct on obj using index
d.obj[d.functext]();
pending…
apply
d.apply();
pending…
apply empty array
d.apply([]);
pending…
apply 1 params
d.apply([1]);
pending…
indirect apply 2 params
d.indirectApply([1, 2]);
pending…
apply 3 params
d.apply([1, 2, 3]);
pending…
apply 5 params
d.apply([1, 2, 3, 4, 5]);
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