Listing containers (docker ps, docker ps -a) - Time & Space Complexity
When we list containers using Docker commands, the time it takes depends on how many containers exist.
We want to understand how the command's work grows as the number of containers increases.
Analyze the time complexity of the following Docker commands.
docker ps
# Lists running containers
docker ps -a
# Lists all containers, including stopped ones
These commands show container information by scanning the container list and displaying details.
Both commands scan through the list of containers one by one.
- Primary operation: Iterating over each container to gather and display its info.
- How many times: Once for each container in the list.
The time to list containers grows directly with the number of containers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 container checks and displays |
| 100 | About 100 container checks and displays |
| 1000 | About 1000 container checks and displays |
Pattern observation: Doubling containers roughly doubles the work done.
Time Complexity: O(n)
This means the command takes longer in direct proportion to how many containers there are.
[X] Wrong: "Listing containers is always instant no matter how many exist."
[OK] Correct: The command must check each container, so more containers mean more work and longer time.
Understanding how commands scale with data size helps you explain system behavior clearly and shows you think about efficiency.
What if Docker cached container info to avoid scanning all containers every time? How would that change the time complexity?