JavaScript performance technique experiment 2
calling a bound function and bind() itself is slow
test code. I ran it on Windows chrome.
/* the prototype to compare with */ function A() { this.val = 1; }; A.prototype.func = function() { return this.val; }; /* B is callee and C is caller */ function B(callback) { this.callback = callback; }; B.prototype.func = function() { this.callback(); }; /* bind once */ function C() { this.b = new B(this.callbackForB.bind(this)); }; C.prototype.func = function() { this.b.func(); }; C.prototype.callbackForB = function() { }; /* D is callee and E is caller */ function D() { }; D.prototype.func = function(callback) { callback(); }; function E() { this.d = new D(); }; /* bind for each calling */ E.prototype.func = function() { this.d.func(this.callbackForD.bind(this)); }; E.prototype.callbackForD = function() { }; /* F is callee and G is caller */ function F(caller, callbackFunc) { this.caller = caller; this.callbackFunc = callbackFunc }; /* use call() */ F.prototype.func = function() { this.callbackFunc.call(this.caller); }; function G() { this.f = new F(this, this.callback); }; G.prototype.func = function() { this.f.func(); }; G.prototype.callback = function() { }; /* H is callee and I is caller */ function H(id, caller) { this.id = id; this.caller = caller; }; /* notify I when be called, like Observer pattern */ H.prototype.func = function() { this.caller.notify(this.id); }; function I() { this.h = new H(this._ID_H, this); }; I.prototype._ID_H = 0; I.prototype.func = function() { this.h.func(); }; I.prototype.notify = function(id) { switch(id) { case this._ID_H: this.funcForH(); break; default: break; } }; I.prototype.funcForH = function() { }; function test(inst) { var oldTime, newTime; var time; var loop = 0x8000000; oldTime = Date.now(); for(var i = 0; i < loop; i++) { inst.func(); } newTime = Date.now(); time = newTime - oldTime; console.log(time); }; var a = new A(); var c = new C(); var e = new E(); var g = new G(); var i = new I(); test(a); test(c); test(e); test(g); test(i);
result
220 45974 386676 2201 894