【问题标题】:What is better for performance creating Function or instance of the constructor Function?创建函数或构造函数函数的实例对性能更好?
【发布时间】:2017-11-23 12:17:28
【问题描述】:

调用函数是否占用与在 javascript node v8.5.0 中创建构造函数实例相同的资源和时间?

我发现他们给我的结果是一样的:

var repo = function () {

var db = {};

var get = function (id) {
    console.log('Getting task ' + id);
    return {
        name: 'new task from db'
    }
 }

var save = function (task) {
    console.log('Saving ' + task.name + ' to the db');
 }

console.log('newing up task repo');
return {
    get: get,
    save: save
 }

}
 module.exports = repo();

当我将 module.exports = repo(); 替换为 module.exports = new repo; 时,它给了我相同的结果,但我需要知道哪个性能更好。

【问题讨论】:

  • 恕我直言,没关系,因为您只有少量的 repo 对象;理想情况下一个。你只会制作一次repo()new repo
  • 差别很小,不值得担心。你应该决定你希望你的函数如何被使用。 new 还是没有new
  • 如果是这样,您使用@deceze 的最佳做法是什么?
  • 我会写一个class来代替这种模块构造函数,然后它会和new一起使用。但是我可能不会导出一个没有机会实例化另一个实例的单例;在那种程度上强制执行单一性根本没有用。

标签: javascript function object constructor


【解决方案1】:

由于您的函数确实已经返回了一个对象,因此它不是传统意义上的构造函数(通过this 关键字初始化实例),不应使用new 调用。更快或更慢甚至都没有关系 - 只是不要这样做。 (提示:new 可能会更慢,因为它必须从 repo.prototype 创建一个新实例,然后将其丢弃)。

当然,在这种情况下完全没有理由使用函数。反正你只调用一次,所以你可以内联代码:

const db = {};
function get(id) {
    console.log('Getting task ' + id);
    return {
        name: 'new task from db'
    }
}
function save(task) {
    console.log('Saving ' + task.name + ' to the db');
}
console.log('newing up task repo');
module.exports = {
    get,
    save
};

甚至简化为

const db = {};
exports.get = function (id) {
    console.log('Getting task ' + id);
    return {
        name: 'new task from db'
    };
};
exports.save = function (task) {
    console.log('Saving ' + task.name + ' to the db');
};
console.log('newing up task repo');

【讨论】:

    【解决方案2】:

    通过使用module.exports = repo();,您正在调用repo函数并将返回值分配给module.export,这里this将指向同一个内存实例

    因此,首先使用module.exports = new repo; 创建新实例并将新实例分配给module.export 在此方法中this 将是不同的内存实例。

    所以简单的术语都取决于用例如何通过指向同一个实例或创建新实例来使用您的代码。

    我希望您了解架构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 2011-04-19
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多