Performance: Dependency injection basics
MEDIUM IMPACT
Dependency injection affects application startup time and runtime memory usage by managing how services and components are created and shared.
import { Injectable } from '@nestjs/common'; @Injectable() export class UserService { getUser() { return { id: 1, name: 'Alice' }; } } import { Controller, Get } from '@nestjs/common'; @Controller('users') export class UserController { constructor(private readonly userService: UserService) {} @Get() getUser() { return this.userService.getUser(); } }
import { Injectable } from '@nestjs/common'; @Injectable() export class UserService { getUser() { return { id: 1, name: 'Alice' }; } } // In a controller or another service const userService = new UserService(); userService.getUser();
| Pattern | Instance Creation | Memory Usage | Startup Time | Verdict |
|---|---|---|---|---|
| Manual service instantiation | Multiple instances per use | High due to duplicates | Slower due to unmanaged creation | [X] Bad |
| NestJS dependency injection | Single shared instance | Lower due to reuse | Faster with centralized control | [OK] Good |