Javascript 原型(prototype)与 $.extend - 内存难题

标签 javascript jquery performance class prototype

相关问题,但没有提及我的具体“错误”-

prototypes vs extending objects

Advantages of using prototype, vs defining methods straight in the constructor?

我有一个我不明白的性能问题。我正在创建一个既可调用又具有方法(类似于 jQuery)的类。

我允许“选择退出”可调用部分,假设使用方法扩展函数比使用原型(prototype)要慢。这个假设在最基本的情况下是正确的。

然而,当我实际对我的代码计时并查看内存使用情况时,我惊讶地发现原型(prototype)方法速度较慢并且占用更多内存。

在调查之后,很明显它只是在调用将 DOM 元素绑定(bind)到“this”的“init”方法时效率较低。如果您注释掉对 init 的调用( fiddle 中的第 49 行),原型(prototype)方法会快得多,正如我所期望的那样。

jsfiddle 在这里 - http://jsfiddle.net/pnsfogem/1/

编辑:jsPerf 在下面列出了 Bergi 的所有建议 - http://jsperf.com/different-types-of-constructors-vs-extend

运行这些 perfs 后,它看起来确实只在我运行的 Chrome 版本中..

以及复制所需的所有代码。

var methods = {
    select: function(selector){
        var $this = this;
        var scopedMethods = {
            newMethod1: function( newParam ){
                $this.newMethod1( selector, newParam );
            },
            newMethod2: function( newParam ){
                $this.newMethod2( selector, newParam );
            }
        };
        return scopedMethods;
    },
    init: function(){
        // console.log(this); // Looks correct for all 2000 elements
        this.$el = $( "<div>" ).appendTo( $("body") );
    },
    newMethod1: function( selector, newParam ){
        // do stuff
    },
    newMethod2: function( selector, newParam ){
        // do stuff
    }
};

function getConstructor( noQuery ){

    var returnedInstance;

    if ( noQuery ){
        var constructor = function(){};
        constructor.prototype = methods;
        returnedInstance = new constructor();
        // Usage:
        // var s = getConstructor( 'justPrototype' );
        // s.newMethod1( '#whatever', 'stuff' );
    }
    else {
        returnedInstance = function(){
            return returnedInstance.select.apply( returnedInstance, arguments );
        };
        $.extend( returnedInstance, methods );
        // Can use either of these ways:
        // var s = getConstructor();
        // s.newMethod1( '#whatever', 'stuff' );
        // s( '#whatever' ).newMethod1( 'stuff' );
    }

    returnedInstance.init();

    return returnedInstance;

}

// When calling init
// This is both faster and more memory efficient. Why?
var arr1 = [];
console.time('normal');
for (var i=0; i<1000;i++){
    arr1.push( getConstructor() );
}
console.timeEnd('normal');
// arr1[0].$el != arr1[1].$el

var arr2 = [];
console.time('prototype');
for (var i=0; i<1000;i++){
    arr2.push( getConstructor( 'justPrototype' ) );
}
console.timeEnd('prototype');
// arr2[0].$el != arr2[1].$el

所以,我的问题是

为什么会这样?我做错了什么吗?

一旦它们被实例化,我希望它们能够处理添加新属性以在性能方面相对相同,但它似乎将原型(prototype)方法的速度降低了 10 倍。

(显然,允许访问原型(prototype)与拥有没有原型(prototype)的函数还有其他好处/权衡,但我认为它们超出了这个问题的范围)

最佳答案

I was creating a class with the ability to be both callable and have methods (similar to jQuery).

不是真的。 jQuery 集合实例不可调用。

Am I doing something wrong?

您的“原型(prototype)”分支看起来有点奇怪。在每次调用时,您都会创建一个新的 constructor 函数。让它全局化应该会有所帮助。此外,带有额外 init 方法的空构造函数是一种非常不寻常的模式。您可能想从构造函数中调用 init 方法(见下文),甚至直接使用

var constructor = methods.init;
constructor.prototype = methods;
function get() {
    …
    return new constructor();
}

如果您只是简单地使用该模式来创建一个以 methods 为原型(prototype)的对象,您应该使用 Object.create :

…  returnedInstance = Object.create(methods);

Once they're instantiated, I would expect them to handle adding new properties to be relatively the same performance wise, but it seems to slow down the prototype approach by 10x.

不,属性优化了很多。使用不寻常的模式会导致速度急剧下降。例如,在 V8(Google Chrome 的 JS 引擎)中,优化了在构造函数调用期间创建的属性,并且没有更多的插槽处于打开状态。当您在构造对象后创建一个新属性时,它可能需要将其内部结构更改为优化程度较低(但对添加属性更友好)的结构,这相当慢。如果这个猜测是正确的,您应该能够通过使用

看到显着的加速
function constructor() {
    this.init();
}
constructor.prototype = methods;
…
return new constructor();

关于Javascript 原型(prototype)与 $.extend - 内存难题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25664525/

相关文章:

python - 可替换多个可迭代对象或与订单无关的产品的高效组合

javascript - 如何将 JSON 导出到 CSV 或 Excel - Angular 2

javascript - 在 IE 11 中打印 Iframe 仅打印第一页

javascript - Jquery移动链式弹出动态定位

binding - jQuery 日期选择器在 AJAX 之后不持久

java - 在没有其他线程等待相同对象成本的对象上调用 notify()

performance - 计算2 * 2矩阵秩的最快方法?

javascript - 剪贴板图像到文件

javascript - Firefox 中的 onmozfullscreenchange 警告(不使用 react )

javascript - 外部 js 文件中的 Symfony 2 翻译