Performance: How dependency injection works in Angular
MEDIUM IMPACT
Dependency injection affects initial load time and runtime responsiveness by managing service creation and reuse efficiently.
import { Injectable, Component } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { constructor() { } } @Component({ selector: 'app-example', template: '<p>Example</p>' }) export class ExampleComponent { constructor(private dataService: DataService) { } }
import { Injectable, Component } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { constructor() { } } @Component({ selector: 'app-example', template: '<p>Example</p>', providers: [DataService] }) export class ExampleComponent { constructor(private dataService: DataService) { } }
| Pattern | Service Instances | Memory Use | Initialization Time | Verdict |
|---|---|---|---|---|
| Service provided in component | Multiple per component | High | Longer due to repeated instantiation | [X] Bad |
| Service provided in root | Single shared instance | Low | Short due to reuse | [OK] Good |