Repository pattern in PHP - Time & Space Complexity
When using the Repository pattern, it's important to understand how the time it takes to get data changes as the data grows.
We want to know how the number of operations grows when fetching or saving many items.
Analyze the time complexity of the following code snippet.
class UserRepository {
private array $users = [];
public function addUser(array $user): void {
$this->users[] = $user;
}
public function findUserByEmail(string $email): ?array {
foreach ($this->users as $user) {
if ($user['email'] === $email) {
return $user;
}
}
return null;
}
}
This code stores users in an array and searches for a user by email using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the users array to find a matching email.
- How many times: Up to once for each user in the array until a match is found or all checked.
As the number of users grows, the search takes longer because it may check more users.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows roughly in direct proportion to the number of users.
Time Complexity: O(n)
This means the time to find a user grows linearly with the number of users stored.
[X] Wrong: "Searching in the repository is always fast and constant time."
[OK] Correct: Because the repository uses a simple array and loops through it, the search time grows as more users are added.
Understanding how data retrieval time grows helps you explain design choices and shows you can think about efficiency in real projects.
"What if we changed the users storage from an array to a hash map keyed by email? How would the time complexity change?"