NestJS object instantiation performance

Viewed 570

in NestJS, it is possible to define injection scope of injectable objects. (possibilities are: singleton, request, transient)

in the doc it is recommend to always use singleton scopes wherever possible, since f.e request scope will make nest instantiate providers on each request-response cycle, which can have an affect on the application's performance

Using request-scoped providers will have an impact on application performance. While Nest tries to cache as much metadata as possible, it will still have to create an instance of your class on each request. Hence, it will slow down your average response time and overall benchmarking result. Unless a provider must be request-scoped, it is strongly recommended that you use the default singleton scope.

Since when Object instantiation consumes so much resources? that the entire framework is built around singleton instances, making those instances kind of "state-full" in the sense where I can't really use "instance variable" safely, without the concern that 2 requests/consumers may use the same provider instance concurrently (due to the async nature of node) and conflict each other's instance variables?

here is what im trying to do:

export class MyClass {
 constructor (...some dependencies) {

 }

 someMethod(payload){
  this.myInstanceVariable = payload.data;
  someMethod2();
 }

 someMethod2(){
  // this.myInstanceVaraible usage, which i cant really trust it contains what i expect it to
 }
}

I come from a ruby background. when i wrote services in ruby, each request would instantiating whatever services it needs, and once the request was done, all those objects would be automatically garbage-collected. that way i could safely define instance-variables on my services - without being concerned about "instances conflicts".

0 Answers
Related