根据每个用户请求创建新实例

Create new instance on every user request

性能问题 - 我想知道如果我有一个由 express 提供支持的节点 http 服务器,在用户发送的每个请求上创建新的 class 实例是否被认为是不好的做法? class 实例从另一个 api 获取数据并公开一些功能来操作获取的数据。

代码示例:

        //--- Handler.js ---
        const _ = require("lodash");

        class Handler {

            constructor() {
                this.fetchData = this.getSiteModel.bind(this);
                this.getA = this.getA.bind(this);
                this.getB = this.getB.bind(this);
                this.getC = this.getC.bind(this);
            }
            
            async fetchData(req,res,id){
              const result = await fetch(...)
              this.data = result;
            }  

            getA(){
            ...
            return this.data.A
            }
            
            getB(){
            ...
              return this.data.B
            }
            
            getC(){
            ...
              return this.data.C
            }
    }

    //---- controller.js ----
    const Handler = require("../Handler/");
    
    exports.getDataById = async function(req ,res) {
         const handler = new Handler();
         return handler.getA();
    }

这样做会更好吗

        //---- controller.js ----
        const fetchData = require("../Handler/");
        const getA = require("../Handler/getA");
        const getB = require("../Handler/getB");
        const getC = require("../Handler/getC");

        exports.getDataById = async function(req ,res) {
              //no new handler instance created
             const data = fetchData(url)
             return getA(data);
        }

Is it considered bad practice to create new class instance on every request sent by the user?

不,这通常不被认为是不好的做法。在处理传入请求期间需要创建对象是正常的。查看在请求处理程序中经常使用的任何数据库查询。它可能会创建多个对象。

现在,是否有更有效的方法来完成您正在做的事情是另一个问题,我们需要查看您的实际代码才能就该主题提供一些建议。

Would it be better to do this instead?

我看不出有太多理由让您在对对象进行单个操作之前将数据放入该对象。

像你提议的那样(添加 await 使其正常工作):

   exports.getDataById = async function(req ,res) {
          //no new handler instance created
         const data = await fetchData(url)
         return getA(data);
    }

我觉得非常好。何时将事物结构化为 class 并将数据放入实例数据以及为什么只使用函数来操作数据是一个 classic OOP 问题,它取决于很多事情所有这些都取决于查看和理解您的真实代码、您正在使用它做什么、将来最有可能扩展它的方式、您在一个请求中对同一数据调用多个函数的频率,等等……