Output escaping with htmlspecialchars in PHP - Time & Space Complexity
We want to understand how the time it takes to escape output with htmlspecialchars changes as the input size grows.
How does the function's work increase when the string gets longer?
Analyze the time complexity of the following code snippet.
<?php
function escapeOutput(string $input): string {
return htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
$text = "<div>Hello & welcome!</div>";
echo escapeOutput($text);
This code takes a string and converts special characters to HTML-safe codes to prevent issues when displaying in a browser.
- Primary operation: The function checks each character in the input string one by one.
- How many times: Once for every character in the string.
As the input string gets longer, the function spends more time checking each character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks |
| 100 | About 100 character checks |
| 1000 | About 1000 character checks |
Pattern observation: The work grows directly with the length of the input string.
Time Complexity: O(n)
This means the time to escape the string grows in a straight line as the string gets longer.
[X] Wrong: "The function runs in constant time no matter the input size because it just calls one function."
[OK] Correct: Even though it is one function call, that function looks at every character, so the time depends on how long the string is.
Understanding how functions like htmlspecialchars scale with input size helps you write safer and efficient code, a skill valued in many coding challenges and real projects.
"What if we used a function that escapes only a fixed set of characters regardless of string length? How would the time complexity change?"