Documentation with comments in Bash Scripting - Time & Space Complexity
We want to see how adding comments affects the time it takes for a bash script to run.
Does writing explanations slow down the script?
Analyze the time complexity of the following code snippet.
#!/bin/bash
# This script prints numbers from 1 to n
n=5
for i in $(seq 1 $n); do
# Print the current number
echo $i
done
This script prints numbers from 1 to n with comments explaining each step.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from 1 to n.
- How many times: It runs exactly n times.
As n grows, the loop runs more times, so the script takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times printing |
| 100 | 100 times printing |
| 1000 | 1000 times printing |
Pattern observation: The number of operations grows directly with n.
Time Complexity: O(n)
This means the script takes longer in a straight line as n gets bigger.
[X] Wrong: "Adding comments makes the script slower because the computer reads them too."
[OK] Correct: Comments are ignored by the computer when running the script, so they do not affect speed.
Understanding what parts of a script affect speed helps you write clear and efficient code.
"What if we added another loop inside the first one? How would the time complexity change?"