javascript - 对 Node 中模块与类的性能影响

标签 javascript node.js

我有两套代码,用来获取结果,我只是想知道这两种方法是否都可以完成。

//dataService.js

module.exports = {
getData: function(){// return data from some sync source}
}

const DataService = require(‘./dataService’);
console.log(DataService.getData());

另一种方式

//dataService.js
var DataService = Class DataService {
  getData (){ / return data from some sync source}
}
module.exports = DataService

const DataService = require(‘./dataService’);
console.log((new DataService()).getData());

请帮助我理解,当我们加载超过 100 万个请求时,这两个代码在性能和标准方面都很好。

最佳答案

我做了一个基准测试,得到了以下结果:

Class Data x 22,047,798 ops/sec ±0.88% (88 runs sampled)
Data as module x 31,695,587 ops/sec ±0.97% (89 runs sampled)

Fastest is Data as module

结果非常合乎逻辑,每次都需要使用new实例化类模块。内存消耗也会更高,新类将返回带有原型(prototype)链的实例。

基准代码:

const Benchmark = require('benchmark');

const moduleData = require('./modules/module-data');
const ClassData = require('./modules/class-data');

var suite = new Benchmark.Suite;

// add tests 
suite.add('Class Data', function () {
  new ClassData().getData();
})
  .add('Data as module', function () {
    moduleData.getData();
  })
  // add listeners 
  .on('cycle', function (event) {
    console.log(String(event.target));
  })
  .on('complete', function () {
    console.log('Fastest is ' + this.filter('fastest').map('name'));
  })
  // run async 
  .run({ 'async': true });

关于javascript - 对 Node 中模块与类的性能影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45997587/

相关文章:

javascript - 如何对未在对象中声明的函数使用对象简写

javascript - 快速验证器如何仅在存在另一个字段时才需要该字段

android - OkHttp Android 发布导致错误 JSON 格式错误

node.js - 使用用于 Nodejs 的 Neo4j-Driver 通过 id 和参数获取 Node

javascript - 算法 : finding nearby value the fastest way

javascript - 如何在 textarea 中使用 google-code-prettify

javascript - Node js从函数返回值

单击任何其他元素时,Javascript 更改 css

mysql - 避免对 Node.js 中的存储过程进行 SQL 注入(inject)

node.js - React-dropzone-uploader AVI 文件卡在状态 "preparing"