【问题标题】:in JavaScript which of these 3 examples has best performance在 JavaScript 中,这 3 个示例中哪个具有最佳性能
【发布时间】: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 使每个实例共享相同的colorsize,方法是将它们放在prototype 上。 JellyFishJellyFish2 具有相同的特征,但会不断修改每个实例的值(但会影响以前的实例)。话虽如此,“best”可能是 JellyFish3,而 move 单独放在 prototype 上。

标签: javascript object closures prototype


【解决方案1】:

为了创建 50 个构造函数... JellyFish1 获胜! http://jsperf.com/jellyfish

用于创建 50 个实例... JellyFish2 获胜! http://jsperf.com/jellyfish-instance

【讨论】:

  • 我猜测试应该创建 1000 个 same 构造函数的实例(如果你可以将 Jellyfish1 称为“构造函数”),而不是创建 1000 个构造函数。
  • 感谢您将 jsperf 的测试用例更新为 1000,它使时差更加明显。
猜你喜欢
  • 2023-03-30
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多