简体   繁体   中英

Node.js performance

Imagine, we got 2 simple classes (omitted export):

class SomeService {
  async func () {
    // some async function logic
    return value;
  }
}

class SomeController {
  constructor (service) {
    this.service = service;
  }
  async func () {
    const value = await this.service.func();
    // some controller-specific logic here
    return value;
  }
}

Also, we got simple function, that use this two classes in two ways.

Case one:

// require clasess

const somefunc = async () => {
  const controller = new SomeController(new SomeService());
  const value = await controller.func();
  return value;
}
module.exports = somefunc;

Case two:

// require clasess
const controller = new SomeController(new SomeService());

const somefunc = async () => {
  const value = await controller.func();
  return value;
}
module.exports = somefunc;

As far as i understand how node's require works in the first case controller will be created each time when the somefunc is called. In the second case controller is created only one time, when the file will be evaluated. What case is better and more importantly what should i read or lookup to understand why?

I imagine the answer depends on your use-case. You have to ask yourself if you need to recreate SomeController every time that the function is called or not. Another thing to also consider is whether SomeController relies on something async when being initialized. For instance, if the controller needs access to a database connection in its constructor, then you'd have to wait for the database connection to be established. In situations like that, you may have no choice but to initialize SomeController inside the function. As I said, there's no objective better in cases like this. It's all dependent on your use-case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM