相关问题,但没有提及我的特定"bug"-
原型与扩展对象
使用原型的优势,与直接在构造函数中定义方法相比?
我有一个性能问题,我不明白。我正在创建一个既可以调用又有方法的类(类似于jQuery)。
我允许"选择退出"可调用部分,假设用方法扩展函数比使用原型要慢。这个假设在最基本的情况下是正确的。
然而,当我实际计时代码并查看内存使用情况时,我惊讶地发现原型方法速度较慢,占用的内存更多
经过研究,很明显,当调用将DOM元素绑定到"this"的"init"方法时,它的效率会降低。如果您注释掉对init的调用(fiddle中的第49行),原型方法会更快,正如我所期望的那样。
jsfiddle在这里-http://jsfiddle.net/pnsfogem/1/
编辑:jsPerf列出了Bergi的所有建议如下-http://jsperf.com/different-types-of-constructors-vs-extend
在运行这些perf之后,它看起来确实只是在我运行的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
所以,我的问题是
为什么会出现这种情况?我做错什么了吗
一旦它们被实例化,我希望它们能够以相对相同的性能来处理添加新属性的问题,但这似乎会将原型方法的速度降低10倍。
(显然,允许访问原型与没有原型的函数相比还有其他好处/权衡,但我认为它们不在这个问题的范围内)
我正在创建一个既可以调用又有方法的类(类似于jQuery)。
不是。jQuery集合实例不可调用。
我做错什么了吗?
您的"原型"分支看起来有点奇怪。在每次调用时,您都会创建一个新的constructor
函数。使其全球化应该会有所帮助。此外,带有额外init
方法的空构造函数是一种非常不寻常的模式。您可能想要从构造函数调用init
方法(见下文),甚至直接使用
var constructor = methods.init;
constructor.prototype = methods;
function get() {
…
return new constructor();
}
如果使用该模式只是为了创建一个以methods
为原型的对象,那么应该使用Object.create
:
… returnedInstance = Object.create(methods);
一旦它们被实例化,我希望它们能够以相对相同的性能来处理添加新属性的问题,但这似乎会将原型方法的速度降低10倍。
不,属性优化了很多。使用不寻常的模式可能会导致速度急剧下降。例如,在V8(Google Chrome的JS引擎)中,在构造函数调用期间创建的属性会得到优化,并且不会留下更多的插槽。当您在构建对象后创建一个新属性时,它可能需要将其内部结构更改为优化程度较低(但更适合添加属性),这相当缓慢。如果这个猜测是正确的,你应该能够通过使用看到显著的加速
function constructor() {
this.init();
}
constructor.prototype = methods;
…
return new constructor();