0
0
NestJSframework~8 mins

Injectable decorator in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Injectable decorator
MEDIUM IMPACT
This affects the dependency injection system's initialization and service instantiation speed, impacting app startup and runtime responsiveness.
Managing service dependencies in a NestJS application
NestJS
@Injectable()
class UserRepository {}

@Injectable()
class UserService {
  constructor(private readonly repo: UserRepository) {}
}
NestJS injects and reuses singleton instances, reducing redundant object creation and improving startup speed.
📈 Performance GainSingle instantiation per service; faster startup and lower memory use.
Managing service dependencies in a NestJS application
NestJS
class UserService {
  constructor() {
    this.repo = new UserRepository();
  }
}

class UserRepository {}
Manually creating dependencies causes tight coupling and repeated instantiation, increasing startup time and memory use.
📉 Performance CostBlocks app startup longer due to manual object creation; no reuse of instances.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual new calls for dependenciesN/AN/AN/A[X] Bad
Using @Injectable with DI containerN/AN/AN/A[OK] Good
Rendering Pipeline
The @Injectable decorator marks classes for NestJS's dependency injection container, which resolves and instantiates dependencies before app runtime.
Initialization
Dependency Resolution
Service Instantiation
⚠️ BottleneckDependency Resolution stage can slow startup if many manual instantiations occur.
Core Web Vital Affected
INP
This affects the dependency injection system's initialization and service instantiation speed, impacting app startup and runtime responsiveness.
Optimization Tips
1Always use @Injectable to let NestJS manage service lifecycles efficiently.
2Avoid manual new calls for dependencies to reduce startup blocking.
3Reuse singleton instances to save memory and improve runtime speed.
Performance Quiz - 3 Questions
Test your performance knowledge
How does using @Injectable improve NestJS app performance?
AIt enables efficient reuse of service instances, reducing startup time.
BIt delays service instantiation until first use, increasing startup time.
CIt forces manual creation of dependencies, increasing memory use.
DIt disables dependency injection, improving runtime speed.
DevTools: Performance
How to check: Record app startup and look for long scripting tasks related to service instantiation.
What to look for: Long blocking times during initialization indicate manual instantiation overhead.