String length (${#var}) in Bash Scripting - Time & Space Complexity
We want to understand how the time it takes to get the length of a string changes as the string gets longer.
Specifically, how does using ${#var} behave when the string size grows?
Analyze the time complexity of the following code snippet.
mystring="Hello, world!"
length=${#mystring}
echo "Length is $length"
This code gets the length of the string stored in mystring and prints it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Counting each character in the string to find its length.
- How many times: Once per character in the string.
As the string gets longer, the time to count its length grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 character checks |
| 100 | 100 character checks |
| 1000 | 1000 character checks |
Pattern observation: The work grows linearly as the string length increases.
Time Complexity: O(n)
This means the time to get the string length grows directly with the number of characters in the string.
[X] Wrong: "Getting the string length is instant no matter how long the string is."
[OK] Correct: The system must check each character to count length, so longer strings take more time.
Knowing how simple operations like string length scale helps you reason about script performance and write efficient code.
"What if the string length was stored in a variable and updated as the string changes? How would that affect the time complexity of getting the length?"