Absolute vs relative paths in Linux CLI - Performance Comparison
When working with file paths in Linux, commands often use absolute or relative paths to find files.
We want to understand how the time to locate a file changes depending on the path type used.
Analyze the time complexity of the following commands.
# Using absolute path
cat /home/user/documents/report.txt
# Using relative path
cat documents/report.txt
These commands read a file using either an absolute or a relative path.
Look at what the system does to find the file.
- Primary operation: Traversing directories in the path to locate the file.
- How many times: Once per directory in the path, step by step.
Finding a file means checking each folder in the path one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 (folders deep) | 3 directory lookups |
| 5 (folders deep) | 5 directory lookups |
| 10 (folders deep) | 10 directory lookups |
Pattern observation: The time grows linearly with the number of folders in the path.
Time Complexity: O(n)
This means the time to find a file grows in direct proportion to how many folders are in its path.
[X] Wrong: "Using an absolute path is always slower because it starts from the root."
[OK] Correct: Both absolute and relative paths require checking each folder in the path, so time depends on path length, not path type.
Understanding how file paths affect command execution helps you reason about system behavior and efficiency in real tasks.
What if the file system used caching for directory lookups? How would that affect the time complexity?