Can Javascript Prototype Pattern Performance Be Improved

I have read that creation of objects via prototypes is faster and uses less memory than closures because closures need to re-create all the functions. Then accessing a function that is on the object's prototype is a little slower because it needs to traverse the prototype chain further to find the function.

I am wondering if adding a reference in the constructor to the prototype function could increase performance with very minimal memory and initial setup impact. This can be achieved with something like this...

function Customer2(name) {
    this.name = name;
    this.greet = this.constructor.prototype.greet;
}
Customer2.prototype = {
    constructor: Customer2,
    greet: function () {
        return this.name + ' says hi!';
    }
};

Here I add a variable this.greet that references the prototype function to save on traversal time.

Could this be an effective method at increasing performance and keeping memory consumption low? Would this cause any side effects such as problems with inheritance?

JSPerf link: http://jsperf.com/prototype-pattern-local-reference

So far the JSPerf seems to slightly support the idea (except Firefox which seems to strongly favor closures for setup which doesn't make any sense, maybe I've done something wrong). Of course, this is a very small example with very few test samples, and it doesn't show memory consumption, but thought it might help.

链接地址: http://www.djcxy.com/p/64170.html

上一篇: 为什么这个函数在长数字比短数字更快运行?

下一篇: 可以改进Javascript原型模式的性能