0
0
Angularframework~8 mins

@Injectable decorator and providedIn in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: @Injectable decorator and providedIn
MEDIUM IMPACT
This concept affects the bundle size and initial load time by controlling service tree-shaking and injection scope.
Providing a service in Angular for dependency injection
Angular
@Injectable({ providedIn: 'root' })
export class DataService {}
Service is tree-shakable and only included if used, reducing bundle size and improving load time.
📈 Performance GainSaves KBs in bundle and speeds up LCP by reducing JS to parse
Providing a service in Angular for dependency injection
Angular
@Injectable()
export class DataService {}

@NgModule({
  providers: [DataService]
})
export class AppModule {}
Service is provided in the module providers array, preventing tree-shaking and increasing bundle size.
📉 Performance CostAdds extra KB to bundle and delays initial load due to larger JS size
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Providing service in NgModule providers000[X] Bad
Using @Injectable({ providedIn: 'root' })000[OK] Good
Rendering Pipeline
The Angular compiler uses the providedIn metadata to decide if a service should be included in the bundle. This affects the JavaScript parsing and execution during page load.
JavaScript Parsing
Execution
Bundle Loading
⚠️ BottleneckBundle Loading and Parsing
Core Web Vital Affected
LCP
This concept affects the bundle size and initial load time by controlling service tree-shaking and injection scope.
Optimization Tips
1Always use providedIn in @Injectable to enable tree-shaking.
2Avoid providing services in NgModule providers unless necessary.
3Smaller bundles improve Largest Contentful Paint (LCP) and user experience.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using providedIn in @Injectable?
AImproves CSS selector matching speed
BAutomatically triggers DOM reflows
CEnables tree-shaking to reduce bundle size
DReduces HTTP requests for images
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and check JS bundle sizes and load times.
What to look for: Smaller bundle size and faster JS load indicate good use of providedIn for tree-shaking.