【发布时间】:2013-07-26 10:23:06
【问题描述】:
这三个函数/对象可以用于相同的目的,我将为每个对象创建新实例。我将分别创建 1000 个,所以我想知道哪个性能最好。
jelly1 = new JellyFish();
jelly2 = new JellyFish2();
jelly3 = new JellyFish3();
//jellyfish object 3
function JellyFish3() {
this.color = "blue";
this.size = "medium";
this.move = function (direction) {
console.log("moving to " + direction);
return direction;
};
}
// jellyfish object 2
function JellyFish2() {};
// constructor
(function (instance) {
instance.color = "blue";
instance.size = "medium";
instance.move = function (direction) {
console.log("moving to " + direction);
return direction;
};
})(JellyFish2.prototype);
// jellyfish object 1
function JellyFish() {
// constructor
(function (instance) {
instance.color = "blue";
instance.size = "medium";
instance.move = function (direction) {
console.log("moving to " + direction);
return direction;
};
})(JellyFish.prototype);
};
【问题讨论】:
-
对其进行基准测试,例如使用 Benchmark.js (benchmarkjs.com)
-
我猜
jellyfish object 2的性能更好!因为它在外部共享通用原型。constructor每次调用内存都会分配 -
他们做不同的事情(最后一个,
JellyFish,完全没用),那你为什么要比较他们的表现呢? -
好吧,当他们不做同样的事情时,哪个更快并不重要。
JellyFish2使每个实例共享相同的color和size,方法是将它们放在prototype上。JellyFish与JellyFish2具有相同的特征,但会不断修改每个实例的值(但会影响以前的实例)。话虽如此,“best”可能是JellyFish3,而move单独放在prototype上。
标签: javascript object closures prototype