Dependency injection concept in PHP - Time & Space Complexity
Understanding Dependency Injection Performance
Dependency injection is a design pattern that affects code structure, not runtime speed. It improves modularity and testability.
Code Comparison
// Bad: Direct instantiation
class UserProfile {
private $db;
public function __construct() {
$this->db = new DatabaseConnection();
}
}
// Good: Injected dependency
class UserProfile {
private $db;
public function __construct(DatabaseConnection $db) {
$this->db = $db;
}
}
Repeating Operations
The constructor runs once per object creation. Injecting vs creating internally has no loop or repeated cost difference.
Growth With Input
Dependency injection does not scale with input size. The pattern is about code organization, so complexity remains constant.
Final Complexity: O(1)
Constructor injection is a single assignment operation regardless of input size.
Common Mistake
Assuming dependency injection adds overhead. The object is created elsewhere and passed in — same cost, better structure.
Interview Connection
Interviewers ask about DI to test understanding of SOLID principles, not performance. Focus on testability and loose coupling.
Self Check
Why does injecting a dependency via constructor not add runtime overhead compared to creating it inside the class?