0
0
NestJSframework~8 mins

DTO class creation in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: DTO class creation
LOW IMPACT
This affects the bundle size and initial load time by adding extra code for data validation and transformation.
Defining data transfer objects (DTOs) for API input validation
NestJS
import { IsString, IsInt, Min, Max } from 'class-validator';

export class CreateUserDto {
  @IsString()
  name: string;

  @IsInt()
  @Min(0)
  @Max(120)
  age: number;
}
Removing unnecessary fields and validations reduces bundle size and speeds up parsing.
📈 Performance Gainsaves ~5kb bundle size, reduces blocking time by 10ms
Defining data transfer objects (DTOs) for API input validation
NestJS
import { IsString, IsInt, Min, Max } from 'class-validator';

export class CreateUserDto {
  @IsString()
  name: string;

  @IsInt()
  @Min(0)
  @Max(120)
  age: number;

  @IsString()
  bio: string;

  @IsString()
  extraLargeField: string; // very large string field not always needed
}
Including large or unnecessary fields and complex validations increases bundle size and slows initial load.
📉 Performance Costadds ~5kb to bundle, blocks rendering for 10-15ms on slow devices
Performance Comparison
PatternBundle Size ImpactExecution TimeValidation ComplexityVerdict
Large DTO with many validations and fieldsHigh (~5kb+)High (10-15ms blocking)Complex[X] Bad
Minimal DTO with essential validations onlyLow (~1-2kb)Low (2-5ms blocking)Simple[OK] Good
Rendering Pipeline
DTO classes are parsed and validated during request handling, affecting JavaScript execution and initial bundle parsing.
JavaScript Parsing
Script Execution
⚠️ BottleneckScript Execution due to validation decorators and metadata processing
Core Web Vital Affected
LCP
This affects the bundle size and initial load time by adding extra code for data validation and transformation.
Optimization Tips
1Keep DTO classes small and focused to reduce bundle size.
2Avoid unnecessary validation decorators to minimize script execution time.
3Use DTOs only for required data fields to improve load speed.
Performance Quiz - 3 Questions
Test your performance knowledge
How does adding many validation decorators to a DTO class affect performance?
ADecreases bundle size but increases execution time
BIncreases bundle size and script execution time
CHas no effect on performance
DOnly affects CSS rendering
DevTools: Performance
How to check: Record a performance profile during app startup or API request handling; look for long script execution times related to DTO validation.
What to look for: Long scripting tasks or blocking time caused by class-validator decorators or metadata reflection.