String interpolation in double quotes in PHP - Time & Space Complexity
We want to see how the time it takes to build a string changes when using double quotes with variables inside.
How does the work grow as the string or variables get bigger?
Analyze the time complexity of the following code snippet.
$name = "Alice";
$age = 30;
$message = "My name is $name and I am $age years old.";
echo $message;
This code creates a message by inserting variables inside a double-quoted string and then prints it.
Look for parts that repeat or take time based on input size.
- Primary operation: Scanning the string to find and replace variables.
- How many times: Once for each character in the string.
As the string gets longer, the work to find variables and build the final string grows too.
| Input Size (string length) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the string length.
Time Complexity: O(n)
This means the time to build the string grows linearly with the string length.
[X] Wrong: "String interpolation is instant and does not depend on string size."
[OK] Correct: The program must check each character to find variables, so bigger strings take more time.
Understanding how string building grows helps you write efficient code and explain your thinking clearly in interviews.
"What if we used single quotes instead of double quotes? How would the time complexity change?"