0
0
PHPprogramming~5 mins

String interpolation in double quotes in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String interpolation in double quotes
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the string gets longer, the work to find variables and build the final string grows too.

Input Size (string length)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The work grows roughly in direct proportion to the string length.

Final Time Complexity

Time Complexity: O(n)

This means the time to build the string grows linearly with the string length.

Common Mistake

[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.

Interview Connect

Understanding how string building grows helps you write efficient code and explain your thinking clearly in interviews.

Self-Check

"What if we used single quotes instead of double quotes? How would the time complexity change?"